【问题标题】:boost::thread yield different results on every runboost::thread 每次运行都会产生不同的结果
【发布时间】:2012-05-02 22:56:09
【问题描述】:

我正在尝试使用 boost::thread 来执行“n”个类似的工作。当然,“n”一般来说可能非常高,所以我想将同时运行的线程数限制为一些小的数字 m(比如 8)。我写了类似下面的东西,我打开 11 个文本文件,使用四个线程一次四个。

我有一个小类parallel(它在调用run() 方法时会打开一个输出文件并向其中写入一行,并接收一个int 变量。编译顺利,程序运行没有任何警告。结果却不如预期。文件已创建,但它们的数量并不总是 11。有谁知道我犯了什么错误?

这里是parallel.hpp:

 #include <fstream>
 #include <iostream>

 #include <boost/thread.hpp>

 class parallel{
 public:
    int m_start;

    parallel()
    {  }

    // member function
    void run(int start=2);
};

parallel.cpp 实现文件是

#include "parallel.hpp"

void parallel::run(int start){

    m_start = start;

    std::cout << "I am " << m_start << "! Thread # " 
          << boost::this_thread::get_id()
          << " work started!" << std::endl;

    std::string fname("test-");
    std::ostringstream buffer;
    buffer << m_start << ".txt";

    fname.append(buffer.str());

    std::fstream output;
    output.open(fname.c_str(), std::ios::out);

    output << "Hi, I am " << m_start << std::endl;

    output.close();

    std::cout << "Thread # " 
          << boost::this_thread::get_id()
          << " work finished!" << std::endl;
}

还有main.cpp:

 #include <iostream>
 #include <fstream>
 #include <string>

 #include <boost/thread.hpp>
 #include <boost/shared_ptr.hpp>

 #include "parallel.hpp"

 int main(int argc, char* argv[]){

     std::cout << "main: startup!" << std::endl;
     std::cout << boost::thread::hardware_concurrency() << std::endl;

     parallel p;

     int populationSize(11), concurrency(3);

     // define concurrent thread group
     std::vector<boost::shared_ptr<boost::thread> > threads;

     // population one-by-one
     while(populationSize >= 0) {
         // concurrent threads
         for(int i = 0; i < concurrency; i++){
             // create a thread
             boost::shared_ptr<boost::thread>
             thread(new boost::thread(&parallel::run, &p, populationSize--));
             threads.push_back(thread);
         }    
         // run the threads
         for(int i =0; i < concurrency; i++)
             threads[i]->join();

         threads.clear();
     }

     return 0;
 }

【问题讨论】:

    标签: c++ threadpool boost-thread


    【解决方案1】:

    您有一个 parallel 对象和一个 m_start 成员变量,所有线程都可以在没有任何同步的情况下访问它。

    更新

    这种竞争条件似乎是设计问题的结果。尚不清楚parallel 类型的对象要表示什么。

    • 如果要表示一个线程,则应为每个创建的线程分配一个对象。发布的程序有一个对象和许多线程。
    • 如果它旨在表示一组线程,则不应保留属于单个线程的数据。

    【讨论】:

    • 这是真的吗?因为创建的文件肯定有不同的索引。
    • 我不确定文件索引是什么。文件具有不同的名称,因为文件系统不允许多个具有相同名称的文件。
    • no-no... 我的代码需要在“test-”的 baseName 之后添加 m_start ...
    • 此外,确实会一次又一次地制作相同的文件(文件名),并且每次运行创建的文件数量都不会增加......如果文件系统限制就是这种情况
    • 确实,您的代码将m_start 附加到test。问题是m_start 的值在任何一个线程中都是未定义的,因为它被所有其他线程覆盖。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    相关资源
    最近更新 更多