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

 首先庆祝下CSDN帐号找回,呵呵1年多没用了。现在潜心研究一些技术方面的东西,大家有兴趣可以多交流交流。


将函数的运行调整为非阻塞模式大家可能平时不怎么用到,但是当大家写插件化程序时,插件是别人写的,为了不影响你的整套流程,可以使用这个方法,当函数运行时间超过你设定的时间时,就认为函数是执行失败。

 

好了,直接上代码。

#include <iostream>
#include "boost/bind.hpp"
#include "boost/thread.hpp"

using namespace std;

void Test()
{
	boost::this_thread::sleep(boost::posix_time::millisec(2000));
}

template<typename f>
bool RunWithOutTimeOut(f fun, boost::int32_t time_tick, boost::int32_t timeout_times)
{
	boost::thread test_thread_(fun);

	boost::int32_t i = 0;
	while (1)
	{
		if (!test_thread_.timed_join(boost::posix_time::millisec(time_tick)))
		{
			if (i ++ >= timeout_times)
			{
				return false;
			}

			continue;
		}
		else
		{
			return true;
		}
	}

	return true;
}

int main()
{
	bool bRet = RunWithOutTimeOut(boost::bind(&Test), 20, 10);
	if (bRet)
	{
		cout << "success" << endl;
	}
	else
	{
		cout << "faild" <<endl;
	}

	int input_data = 0;
	cin >> input_data;
	return 1;
}

OK了,大家应该都懂,我就不多说了。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值