【问题标题】:Interrupting a boost::thread while interruptions are disabled在禁用中断时中断 boost::thread
【发布时间】:2011-03-02 16:48:52
【问题描述】:

在使用 boost::threads 时,我遇到了这个中断问题。当我在线程 B 上从线程 A 执行 boost::thread_interrupt 时,而 B 禁用了中断(boost::this_thread::disable_interrupts di),中断似乎丢失了。 也就是说,如果我在启用中断后放置一个 boost::thread::interruption_point() ,它不会抛出 boost::thread_interrupted 异常。

这是预期的行为还是我做错了什么?

谢谢

【问题讨论】:

    标签: boost boost-thread interrupted-exception


    【解决方案1】:

    文档中没有任何内容说当线程 B 重新启用中断时会重新触发中断。我试过一个简单的测试程序,可以确认你描述的行为。

    重新启用中断后,您可以检查this_thread::interruption_requested() 以查看在禁用中断时是否请求中断。如果确实请求中断,您可以自己抛出thread_interrupted 异常。

    这是一个演示这个的工作程序:

    #include <boost/thread.hpp>
    #include <iostream>
    
    using namespace std;
    using namespace boost;
    
    void threadB()
    {
        int ticks = 0;
        this_thread::disable_interruption* disabler = 0;
        try
        {
            while (ticks < 20)
            {
                if (ticks == 5)
                {
                    cout << "Disabling interruptions\n";
                    disabler = new this_thread::disable_interruption;
                }
                if (ticks == 15)
                {
                    cout << "Re-enabling interruptions\n";
                    delete disabler;
                    if (this_thread::interruption_requested())
                    {
                        cout << "Interrupt requested while disabled\n";
                        throw thread_interrupted();
                    }
                }
                cout << "Tick " << ticks << "\n";
                thread::sleep(get_system_time() + posix_time::milliseconds(100));
                ++ticks;
            }
        }
        catch (thread_interrupted)
        {
            cout << "Interrupted\n";
        }
    }
    
    int main()
    {
        thread b(&threadB);
        thread::sleep(get_system_time() + posix_time::milliseconds(1000));
        b.interrupt();
        cout << "main -> Interrupt!\n";
        b.join();
    }
    

    希望这会有所帮助。

    【讨论】:

    • 我必须说boost::thread 越来越漂亮了!之前,我必须使用互斥锁保护的布尔变量手动实现自己的中断机制。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多