[英]Boost Thread - How to acknowledge interrupt
我有阻塞任务,将由find_the_question()函数执行。 但是,我不希望线程执行此函数需要超过10秒。 因此,如果它需要超过10秒,我想关闭该线程清理所有资源。
我尝试为此编写代码,但不知何故,如果线程占用时间超过10秒,我无法在find_the_question()函数中获得中断。 你能告诉我我做错了什么吗?
void find_the_question(std::string value)
{
//allocate x resources
try{
//do some process on resources
sleep(14);
//clean resources
}
catch(boost::thread_interrupted const& )
{
//clean resources
std::cout << "Worker thread interrupted" << std::endl;
}
}
int main()
{
boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(10000);
std::cout << "In main" << std::endl;
boost::thread t1(find_the_question, "Can you block me");
t1.interrupt();
if (t1.timed_join(timeout))
{
//finished
std::cout << "Worker thread finished" << std::endl;
}
else
{
//Not finished;
std::cout << "Worker thread not finished" << std::endl;
}
std::cout << "In main end" << std::endl;
}
输出:如果t1需要10秒以上才能完成,我将得到以下控制台输出。
std::cout << "In main" << std::endl;
std::cout << "Worker thread not finished" << std::endl;
std::cout << "In main end" << std::endl;
然而,我期待以下输出
std::cout << "In main" << std::endl;
std::cout << "Worker thread interrupted" << std::endl;
std::cout << "Worker thread not finished" << std::endl;
std::cout << "In main end" << std::endl;
你能告诉我我做错了什么吗?
提前致谢
对于使用boost :: thread :: interrupt(),你必须使用boost :: thread :: sleep()才能工作。
可以通过调用相应的boost :: thread对象的interrupt()成员函数来中断正在运行的线程。 当被中断的线程接下来执行一个指定的中断点(或者如果它在执行一个时当前被阻塞)并且启用了中断,则在被中断的线程中将抛出boost :: thread_interrupted异常。 如果没有捕获,这将导致中断线程的执行终止。 与任何其他异常一样,堆栈将被展开,并且将执行自动存储持续时间对象的析构函数
预定义的中断点:
以下函数是中断点,如果为当前线程启用了中断,则会抛出boost :: thread_interrupted,并为当前线程请求中断:
boost::thread::join()
boost::thread::timed_join()
boost::condition_variable::wait()
boost::condition_variable::timed_wait()
boost::condition_variable_any::wait()
boost::condition_variable_any::timed_wait()
boost::thread::sleep()
boost::this_thread::sleep()
boost::this_thread::interruption_point()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.