1

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

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

谢谢

4

1 回答 1

4

文档中没有说明当线程 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();
}

希望这可以帮助。

于 2011-03-02T19:38:09.553 回答