Task: in parallel to read the files and output to the console the file name and number from the file.

Code:

#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <vector> #include <boost\filesystem.hpp> #include <boost\filesystem\fstream.hpp> #include <boost\thread\thread.hpp> using namespace std; namespace fs = boost::filesystem; vector<int> values; FILE* txt; fs::path path("c:\\text"); std::vector<boost::thread> threads; int result = 0; void readFile(fs::directory_iterator it) { fs::ifstream ifs(*it); if (ifs.is_open()) { int val; ifs >> val; //values.push_back(val); result += val; cout << it->path().filename() << ": " << val << endl; txt = fopen(it->path().string().c_str(), "r"); fclose(txt); boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); } else { cerr << "Ошибка!" << endl; } } int main() { setlocale(LC_ALL, "rus"); cout << "Введите путь к файлам (*.txt) (например C:\\text): "; cin >> path; cout << endl; for (fs::directory_iterator it(path); it != fs::directory_iterator(); ++it) { if (it->path().extension() == ".txt") { threads.push_back(boost::thread(&readFile, it)); } } boost::this_thread::sleep(boost::posix_time::milliseconds(1000)); cout << "Сумма всех чисел: " << result << endl; system("pause"); return 0; } 

As a result, Krakazyabra is output to the console. enter image description here

But if every new thread is called up with a delay, then everything is fine enter image description here

How to solve a problem?

  • And to synchronize the output, for example, using at least a mutex is not destiny? - Harry
  • It would be "fate" - there would be no question. - Vitali
  • Do you want without mutexes? - KoVadim
  • Then synchronize the output messages in a separate thread. Is it possible or also beyond the limits? - Harry
  • It would be desirable, that there would be a correct conclusion. If it can be done mutexes, answer as. - Vitali

1 answer 1

Try adding to global variables:

 std::mutex cout_m; 

And in the stream line

 cout << it->path().filename() << ": " << val << endl; 

write as

 { std::lock_guard<std::mutex> lock(cout_m); cout << it->path().filename() << ": " << val << endl; } 
  • Already tried. pp.vk.me/c639917/v639917894/1328/nrypMV2a_Ss.jpg in the files of the number 1, 10, 100 ... The correct result should be 1111111 - Vitaly
  • Well, you only talked about withdrawal. In order to correctly count the amounts, the string result += val; also need to be made under the protection of the mutex ... - Harry