boost disable_interruption不会阻止thread_interrupted

时间:2011-08-07 22:16:15

标签: c++ boost boost-thread

我正在尝试防止线程在特定范围内时中断。但是,使用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();
}

文档似乎暗示boost::this_thread::sleep()boost::thread_interrupted在范围内时不会抛出di

我做错了什么?

1 个答案:

答案 0 :(得分:5)

您应该删除以下行中的括号:

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

您没有创建disable_interruption对象,而是声明了函数di。