简体   繁体   English

使用线程c ++时打印重复项

[英]printing duplications when using threads c++

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).原始代码假设在 txt 文件上写入我的一些计算结果,但在这里我将其更改为写入数字 1(以简化代码)。 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...问题是我没有得到我想得到的数量……而不是 1000 次打印,我每次运行都会得到一个更大的随机数 1……

What is the problem with my code?我的代码有什么问题?

(I'm using windows 10, codeblock workspace, I'm writing the code in c++) (我使用的是 Windows 10,代码块工作区,我正在用 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.使 ofstream 线程安全。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM