天天看点

创建函数的非阻塞运行模式2

       上一篇介绍了一种非阻塞模式的运行,可以解决大部分的问题,可是无法获取函数执行后的返回值,这个当然可以通过改变接口,将返回值以参数的引用形式传入,在一定程度上可以规避这种问题,下面介绍一种可以获取到函数返回值的方式。(上一篇中对于函数在超时情况下还未返回,建议用户杀死线程,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).否则返回程序执行的结果。