Задача: параллельно читать файлы и выводить в консоль имя файла и цифру из файла.
Код:
#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;
}
В итоге в консоль выводится краказябра
Но если каждый новый поток вызывать с задержкой, то всё нормально
Как решить проблему?