[英]printing duplications when using threads c++
我正在尝试为我的更大程序编写基本代码。 原始代码假设在 txt 文件上写入我的一些计算结果,但在这里我将其更改为写入数字 1(以简化代码)。 问题是我没有得到我想得到的数量……而不是 1000 次打印,我每次运行都会得到一个更大的随机数 1……
我的代码有什么问题?
(我使用的是 Windows 10,代码块工作区,我正在用 C++ 编写代码)
编码:
#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;
}
谢谢你们!
使 ofstream 线程安全。 以下会做。
#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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.