c++ 终止 超时,C ++:如何实现任意函数调用的超时?

I need to call a library function that sometimes won't terminate within a given time, unfortunately. Is there a way to call the function but abort it if it doesn't terminate within n seconds?

I cannot modify the function, so I cannot put the abort condition into it directly. I have to add a timeout to the function externally.

Is it maybe a possible solution to start it as a (boost) thread, which I can then terminate after a certain time? Would something like that work? I actually believe the function is not thread-safe, but that wouldn't matter if I run it as the only single thread, right? Are there other (better) solutions?

解决方案

You could spawn a boost::thread to call the API:

boost::thread api_caller(::api_function, arg1, arg2);

if (api_caller.timed_join(boost::posix_time::milliseconds(500)))

{

// API call returned within 500ms

}

else

{

// API call timed out

}

Boost doesn't allow you to kill the worker thread, though. In this example, it's just orphaned.

You'll have to be careful about what that API call does, because it may never release resources it's acquired.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值