【发布时间】:2011-06-21 10:32:26
【问题描述】:
我正在使用 boost 线程来并行化我的程序中的计算。控制器对象管理计算作业和结果。我创建了一堆工作线程,它们从控制器对象获取它们的工作,而主线程显示结果。结果需要以正确的顺序显示。为了实现这一点,我在std::deque 中使用了 boost 期货。 GetNewJob() 在双端队列的末尾添加一个新的 boost::promise 并返回一个指针。 GetNextResult() 从队列的前端获取结果。如果还没有准备好结果,它会阻塞调用线程。
我的 Controller 类的重要部分:
class Controller
{
public:
Controller();
boost::shared_ptr<boost::promise<Results> > GetNewJob();
Results GetNextResult();
class NoJobsLeft{};
class NoResultsLeft{};
private:
bool JobsLeft() const;
bool ResultsLeft() const;
std::deque<boost::shared_ptr<boost::promise<Results> > > queue_;
boost::mutex mutex_;
boost::condition_variable condition_;
};
工人函数:
void DoWork()
{
try
{
while(true)
{
boost::shared_ptr<boost::promise<Results> >
promise(controller.GetNewJob());
//do calculations
promise->set_value(results);
}
}
catch(NoJobsLeft)
{
}
}
主程序代码:
Controller controller(args);
boost::thread_group worker_threads;
for (unsigned i = 0; i < n_cpus; ++i)
worker_threads.create_thread(DoWork);
try
{
while(true)
{
Results results = controller.GetNextResult();
std::cout << results;
std::cout << std::endl;
}
}
catch(NoResultsLeft)
{
}
worker_threads.join_all();
有时这很好用,所有结果都会显示出来。 但很多时候我根本看不到任何输出。
我不在工作线程中使用cout。
GetNewJob()、GetNextResult()的实现:
boost::shared_ptr<boost::promise<Results> > Controller::GetNewJob()
{
boost::lock_guard<boost::mutex> lock(mutex_);
if (!JobsLeft())
throw NoJobsLeft();
//determine more information about the job, not important here
queue_.push_back(boost::make_shared<boost::promise<Results> >());
condition_.notify_one();
return queue_.back();
}
Results Controller::GetNextResult()
{
boost::shared_ptr<boost::promise<Results> > results;
{
boost::unique_lock<boost::mutex> lock(mutex_);
if (!ResultsLeft())
throw NoResultsLeft();
while(!queue_.size())
{
condition_.wait(lock);
}
results = queue_.front();
queue_.pop_front();
}
return results->get_future().get();
}
bool Controller::ResultsLeft() const
{
return (queue_.size() || JobsLeft()) ? true : false;
}
【问题讨论】:
-
@Fredrik:
std::endl隐式刷新流。 -
那我今天学到了新东西!谢谢
-
你能告诉我们
GetNewJob()和GetNextResult()函数的实现吗?
标签: c++ multithreading boost-thread cout