c++ - 为什么要测试 interruption_requested() 时使用 boost disable_interruption?

标签 c++ multithreading boost-thread

我在很多地方看到这样的代码:

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/

相关文章:

c++ - 如何将元素插入 std::unordered_map<int, vector<Object*>>

c++ - 迭代我的对象停止工作

c++ - boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<boost::thread_resource_error>>

boost - 为什么我们需要 boost::thread_specific_ptr?

c++ - C++ 中的异步函数

c++ - 如果我只需要其中的几个函数,是否值得包含一个大型 C++ 库?

c++ - 从 -30 到 30

C++:OpenMP:为多线程复制函数指针

Java基本线程池带锁的实现.ReentrantLock

python - Python多重处理启动进程,但只有一个处于事件状态