boost disable_interruption not preventing thread_interrupted

boost disable_interruption not preventing thread_interrupted

本文关键字:thread interrupted preventing interruption disable boost not      更新时间:2023-10-16

我试图防止线程在特定范围内中断。然而,使用boost::this_thread::disable_interruption di()似乎没有任何效果。

#include <boost/thread.hpp>
#include <iostream>
void worker() {
    std::cout << "START" << std::endl;
    for(;;) {
        {
            boost::this_thread::disable_interruption di();
            try {
                boost::this_thread::sleep(boost::posix_time::seconds(1));
            }
            catch(boost::thread_interrupted & e) {
                assert( false );
            }
        }
        try {
            boost::this_thread::interruption_point();
        }
        catch(boost::thread_interrupted & e) {
            break;
        }
    }
    std::cout << "END" << std::endl;
}

int main() {
    boost::thread thread(&worker);
    thread.interrupt();
    thread.join();
}

文档似乎暗示当di在作用域中时,boost::this_thread::sleep()不会抛出boost::thread_interrupted

我做错了什么?

你应该去掉下面一行中的括号:

//boost::this_thread::disable_interruption di();
boost::this_thread::disable_interruption di;

不是创建disable_interruption对象,而是声明函数di。