上一篇介紹了一種非阻塞模式的運作,可以解決大部分的問題,可是無法擷取函數執行後的傳回值,這個當然可以通過改變接口,将傳回值以參數的引用形式傳入,在一定程度上可以規避這種問題,下面介紹一種可以擷取到函數傳回值的方式。(上一篇中對于函數在逾時情況下還未傳回,建議使用者殺死線程,detach的操作其實沒啥用,隻是放棄對那個線程的管理而已,線程還在)
#include "boost/thread/future.hpp"
#include "boost/thread.hpp"
#include "boost/optional.hpp"
#include "boost/utility/result_of.hpp"
int add(int a, int b)
{
return (a + b);
}
template<typename result_type, typename fun>
boost::optional<result_type> GetFuture(fun f)
{
boost::packaged_task<result_type> add_task(f);
boost::unique_future<result_type> add_result = add_task.get_future();
boost::thread work_thread(boost::move(add_task));
if (!add_result.timed_wait(boost::posix_time::milliseconds(2000)))
{
return boost::optional<result_type>(boost::none);
}
work_thread.join();
if (add_result.is_ready() && add_result.has_value())
{
return boost::optional<result_type>(add_result.get());
}
else
{
return boost::optional<result_type>(boost::none);
}
}
void Test_BoostFuture()
{
boost::optional<boost::int32_t>res = GetFuture<boost::int32_t>(boost::bind(&add, 3, 5));
};
int main()
{
Test_BoostFuture();
return 1;
}
這種方式在比上一種方式應該要很多,如果函數逾時,那麼傳回的是option<result_type>(none).否則傳回程式執行的結果。