我一直在忙于Boost的未来,并想知道如果他们是一个可接受和安全的方法来检查一个单独的线程是否已完成。期货是否是检查单个线程完成的安全方法?
我以前从未使用过它们,所以我写的大部分代码都是基于Boost's Synchronization documentation。
#include <iostream>
#include <boost/thread.hpp>
#include <boost/thread/future.hpp>
int calculate_the_answer_to_life_the_universe_and_everything()
{
boost::this_thread::sleep(boost::posix_time::seconds(10));
return 42;
}
int main()
{
boost::packaged_task<int> task(calculate_the_answer_to_life_the_universe_and_everything);
boost::unique_future<int> f(task.get_future());
boost::thread th(boost::move(task));
while(!f.is_ready())
{
std::cout << "waiting!" << std::endl;
boost::this_thread::sleep(boost::posix_time::seconds(1));
}
std::cout << f.get() << std::endl;
th.join();
}
这似乎等待calculate_the_answer_to_life_the_universe_and_everything()线程返回42.难道事情可能出差错呢?
谢谢!
好了,你可以检查将来的结果是否准备好。我想,产生结果的线程不一定必须终止。 –
当然,忙着等待睡觉并不是正确的做法。不过,您可能将其编写为演示代码。 – usr