下面的进程函数从队列中读取数据并对其进行处理。wait_and_pop函数masterQueue执行阻塞调用。因此,在队列中存在可以读取的数据之前,控件不会向前移动。
class Context
{
void launch()
{
boost::thread thread1(boost::bind(&Context::push,this ) );
boost::thread thread2(boost::bind(&Context::process,this ) );
std::cout<<"Joining Thread1"<<std::endl;
thread1.join();
std::cout<<"Joining Thread2"<<std::endl;
thread2.join();
}
void process()
{
Data data;
while(status)
{
_masterQueue.wait_and_pop(data); //Blocking Call
//Do something with data
}
}
void push()
{
while(status)
{
//Depending on some internal logic, data is generated
_masterQueue.push(data);
}
}
};状态是布尔值(在全局范围内)。默认情况下,此布尔值设置为true。只有当信号被捕获时,如SIGINT、SIGSESV等,才会将其更改为假。在这种情况下,可以退出when循环,并且程序可以安全退出。
bool status = true;
void signalHandler(int signum)
{
std::cout<<"SigNum"<<signum;
status = false;
exit(signum);
}
int main()
{
signal(SIGABRT, signalHandler);
signal(SIGINT, signalHandler);
signal(SIGSEGV, signalHandler);
Context context;
context.launch();
}由于当抛出信号时,thread2不推送新的数据,所以thread1中的控件被卡在
_masterQueue.wait_and_pop(data);我如何迫使这个阻塞呼叫被中断?
发布于 2015-06-04 06:42:05
超时--实际上是你的答案--你在得到答案或中断时中断了循环。
您还可以通过让插入中断将一个noop推送到队列中来稍微欺骗一些事情。
发布于 2015-06-04 09:12:05
当需要完成时,您可以尝试.interrupt()线程。
如果.wait_and_pop()使用标准的boost机制来等待(条件变量或类似),那么即使在阻塞状态下,它也一定会通过抛出boost::thread_interrupted异常而被中断。如果您的masterQueue类是可靠的wrt异常,那么这种中断是安全的。
https://stackoverflow.com/questions/30636619
复制相似问题