【发布时间】:2015-04-12 23:21:41
【问题描述】:
我正在使用boost interprocess library 创建服务器和客户端程序,以便在共享内存中传递opencv mat objects。每个服务器和客户端进程都有两个 boost 线程,它们是 boost::thread_group 的成员。一个处理命令行 IO,而另一个管理数据处理。共享内存访问使用 boost::interprocess condition_variables 同步。
由于这个程序涉及共享内存,我需要在退出前进行一些手动清理。我的问题是,如果服务器过早终止,则客户端上的处理线程会在 wait() 调用处阻塞,因为服务器负责发送通知。我需要以某种方式中断卡在wait() 的线程以启动共享内存销毁。我了解在线程上调用interrupt()(在我的情况下为thread_group.interrupt_all())将导致在到达中断点(例如wait())时抛出boost::thread_interrupted 异常,这如果不处理,将允许共享内存破坏继续进行。但是,当我尝试在wait() 中中断线程时,似乎什么也没有发生。例如,这不会在命令行中打印任何内容:
try {
shared_mat_header->new_data_condition.wait(lock);
} catch (...) {
std::cout << "Thread interrupt occurred\n";
}
我完全不确定,但似乎interrupt() 调用需要在线程进入wait() 之前发生才能引发异常。这是真的?如果不是,那么中断被 condition_variable.wait() 调用阻塞的 boost 线程的正确方法是什么?
感谢您的任何见解。
编辑
我接受了 Chris Desjardins 的回答,它没有直接回答问题,但具有预期的效果。在这里,我将他的代码 sn-p 翻译为与boost::interprocess 条件变量一起使用,其语法与boost::thread 条件变量略有不同:
while (_running) {
boost::system_time timeout = boost::get_system_time() + boost::posix_time::milliseconds(1);
if (shared_mat_header->new_data_condition.timed_wait(lock, timeout))
{
//process data
}
}
【问题讨论】:
标签: c++ multithreading opencv boost