禁用中断时中断boost::线程
在使用boost::threads时,我遇到了这个中断问题。当我从线程B上的线程a执行boost::thread_中断时,而B禁用了中断(boost::this_thread::disable_interrupts di),中断似乎丢失了。 也就是说,如果我在启用中断后放置boost::thread::interruption\u point(),它不会抛出boost::thread\u Interruptive异常 这是预期的行为还是我做错了什么禁用中断时中断boost::线程,boost,boost-thread,interrupted-exception,Boost,Boost Thread,Interrupted Exception,在使用boost::threads时,我遇到了这个中断问题。当我从线程B上的线程a执行boost::thread_中断时,而B禁用了中断(boost::this_thread::disable_interrupts di),中断似乎丢失了。 也就是说,如果我在启用中断后放置boost::thread::interruption\u point(),它不会抛出boost::thread\u Interruptive异常 这是预期的行为还是我做错了什么 谢谢文档中没有任何内容说明当线程B重新启用中断
谢谢文档中没有任何内容说明当线程B重新启用中断时会重新触发中断。我试过一个简单的测试程序,可以确认你描述的行为 重新启用中断后,可以检查
此线程::interruption\u requested()
,查看在禁用中断时是否有请求的中断。如果确实请求了中断,您可以自己抛出一个thread\u 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();
}
#包括
#包括
使用名称空间std;
使用名称空间boost;
void threadB()
{
int ticks=0;
此线程::禁用中断*disabler=0;
尝试
{
而(滴答声<20)
{
如果(刻度==5)
{
cout文档中没有说明当线程B重新启用中断时会重新触发中断。我已经尝试了一个简单的测试程序,可以确认您描述的行为
重新启用中断后,您可以检查此线程::interruption\u requested()
,查看在禁用中断时是否有请求的中断。如果确实请求了中断,您可以自己抛出线程中断的
异常
下面是一个工作程序,演示了这一点:
#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();
}
#包括
#包括
使用名称空间std;
使用名称空间boost;
void threadB()
{
int ticks=0;
此线程::禁用中断*disabler=0;
尝试
{
而(滴答声<20)
{
如果(刻度==5)
{
我必须说,boost::thread
变得非常灵活!以前,我必须用互斥保护的布尔变量手动实现我自己的中断机制。我必须说,boost::thread
变得非常灵活!以前,我必须用互斥保护的布尔变量手动实现我自己的中断机制。