在使用boost::Threads时,我遇到了这个中断问题。当我在线程B上从线程A执行boost::thread_interrupt时,而B禁用了中断(boost::this_thread::disable_interrupts di),中断似乎丢失了。也就是说,如果我在启用中断之后放入一个boost::thread::interruption_point(),它不会抛出boost::thread_interrupted异常。
这是预期的行为,还是我做错了什么?
谢谢
发布于 2011-03-03 03:38:10
文档中没有提到,当线程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();
}希望这能有所帮助。
https://stackoverflow.com/questions/5170647
复制相似问题