【发布时间】: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(¶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;
}
【问题讨论】:
标签: c++ threadpool boost-thread