我在很多地方看到这样的代码:
void threadFunction()
{
boost::this_thread::disable_interruption disable;
while (!boost::this_thread::interruption_requested())
{
//do stuff
}
}
对我来说,这看起来像是我“禁用”了线程函数被中断,但随后我再次测试中断。 奇迹般地,它起作用了。 有人可以向我解释它在幕后的实际作用吗? 谢谢!
最佳答案
disable_interruption
防止线程实际被中断;它不会阻止设置中断状态。然后 interruption_requested
测试是否设置了中断状态。
请参阅 Boost 文档:特别是 the "Interruption" section
各种方法被归类为“中断点”,如果在请求中断时调用它们将抛出异常,除非中断已被禁用。
简而言之:
- 禁用中断可防止中断实际停止线程,但中断仍将线程标记为“已请求中断”
interruption_requested
方法检查是否已请求中断
关于c++ - 为什么要测试 interruption_requested() 时使用 boost disable_interruption?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29099617/