我一直在忙於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