C ++:如何实现任意函数调用的超时? [英] C++: How to implement a timeout for an arbitrary function call?

查看:1165
本文介绍了C ++:如何实现任意函数调用的超时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要调用一个库函数,有时不会在给定的时间内终止,不幸的是。是否有一种方法来调用函数,但如果它在 n 秒内没有终止,则中止它?

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?

推荐答案

您可以生成一个 boost :: thread 调用API:

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允许你杀死工作线程,虽然。在这个例子中,它只是孤立的。

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

你必须小心这个API调用是什么,因为它可能永远不会释放它获取的资源。

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

这篇关于C ++:如何实现任意函数调用的超时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆