文档中没有说明当线程 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();
}
希望这可以帮助。