在一个单独的线程 (std::thread
) 中,我有一个等待 xcb_wait_for_event
的事件循环。当程序退出时,我想通过中断(我有一个设置线程局部变量的解决方案,循环中的检查点抛出异常)来很好地关闭程序,然后将我的事件线程加入主线程。问题是 xcb_wait_for_event
;我需要一种尽早从它返回的方法,或者我需要该函数的替代方法。
谁能提出解决方案?感谢您的帮助!
最佳答案
我相信我已经想出了一个合适的解决方案。我已将 xcb_wait_for_event
替换为以下函数:
xcb_generic_event_t *WaitForEvent(xcb_connection_t *XConnection)
{
xcb_generic_event_t *Event = nullptr;
int XCBFileDescriptor = xcb_get_file_descriptor(XConnection);
fd_set FileDescriptors;
struct timespec Timeout = { 0, 250000000 }; // Check for interruptions every 0.25 seconds
while (true)
{
interruptible<std::thread>::check();
FD_ZERO(&FileDescriptors);
FD_SET(XCBFileDescriptor, &FileDescriptors);
if (pselect(XCBFileDescriptor + 1, &FileDescriptors, nullptr, nullptr, &Timeout, nullptr) > 0)
{
if ((Event = xcb_poll_for_event(XConnection)))
break;
}
}
interruptible<std::thread>::check();
return Event;
}
利用 xcb_get_file_descriptor
,我可以使用 pselect
等待直到有新事件,或者直到发生指定的超时。这种方法产生的额外 CPU 成本可以忽略不计,固定为 0.0%(在此 i7 上)。唯一的“缺点”是最多需要等待 0.25 秒来检查中断,我确信可以安全地降低该限制。
关于c++ - 如何中断 xcb_wait_for_event?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30387126/