I'm trying to write a basic code for my bigger program. The original code suppose to write on a txt file some results of my calculations but here I changed it to write the numer 1 (to simplify the code). The problem is that I dont get the number of ones I suppose to get... instede of 1000 prints of 1 I get a bigger and random number of 1 each running...
What is the problem with my code?
(I'm using windows 10, codeblock workspace, I'm writing the code in c++)
The code:
#include <iostream>
#include <thread>
#include <vector>
#include <fstream>
using namespace std;
ofstream myfile;
void doTask()
{
myfile << "1\n";
}
void f()
{
vector<thread> threads;
for(int i = 0; i < 10; ++i)
{
threads.push_back(thread(doTask));
}
for(int j=0; j<10; j++) threads[j].join();
threads.erase(threads.begin(), threads.end());
}
int main()
{
myfile.open("a.txt");
for(int i=0; i<100; i++) f();
myfile.close();
return 0;
}
Thank you all!
Make ofstream thread safe. Following will do.
#include <iostream>
#include <thread>
#include <vector>
#include <fstream>
#include <mutex>
using namespace std;
ofstream myfile;
std::mutex myMutex;
void doTask()
{
myMutex.lock();
myfile << "1\n";
myMutex.unlock();
}
void f()
{
vector<thread> threads;
for(int i = 0; i < 10; ++i)
{
threads.push_back(thread(doTask));
}
for(int j=0; j<10; j++) threads[j].join();
threads.erase(threads.begin(), threads.end());
}
int main()
{
myfile.open("a.txt");
for(int i=0; i<100; i++) f();
myfile.close();
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.