boost :: thread在每次运行时产生不同的结果
问题描述:
我想利用boost :: thread来执行“n”个类似的工作。当然,“n”通常可能会很高,所以我想限制同时运行的线程的数量为一些小数目m(比如8)。我写了类似下面的内容,在这里我打开了11个文本文件,每次使用四个线程四个文件。boost :: thread在每次运行时产生不同的结果
我有一个小的类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(¶llel::run, &p, populationSize--));
threads.push_back(thread);
}
// run the threads
for(int i =0; i < concurrency; i++)
threads[i]->join();
threads.clear();
}
return 0;
}
答
您有与单个m_start
成员变量,其所有线程没有任何同步访问单个parallel
对象。
更新
这种竞争状态似乎是一个设计问题的结果。目前还不清楚parallel
类型的目标是什么意思。
- 如果它是为了表示一个线程,那么应该为每个创建的线程分配一个对象。发布的程序有一个对象和许多线程。
- 如果它是为了表示一组线程,那么它不应该保留属于单个线程的数据。
是真的吗?对于创建的文件肯定有不同的索引。 – 2012-04-21 19:40:17
我不确定文件索引是什么。文件具有不同的名称,因为文件系统不允许具有相同名称的多个文件。 – 2012-04-21 19:51:28
no-no ...我的代码需要在“test-”的baseName后加m_start ... – 2012-04-21 20:17:05