Cross-Platform equivalent to windows events(跨平台等价于windows事件)
问题描述
我正在尝试将一些 Windows 代码移植到 Linux,理想情况下是通过独立于平台的库(例如 boost),但是我不确定如何移植这部分事件代码.
I'm trying to port some Windows code to Linux, ideally through platform-independent libraries (eg boost), however I'm not sure how to port this bit of event code.
这段代码涉及两个线程(我们称它们为 A 和 B).A 想做一些只有 B 才能做的事情,所以它向 B 发送一条消息,然后等待 B 说它完成了.在 Windows 中,这看起来像:
The bit of code involves two threads (lets call them A and B). A wants to do something that only B can, so it sends B a message, then waits for B to say its done. In windows this looks something like:
void foo();//thread a calls this
void bar(HANDLE evt);
void foo()
{
HANDLE evt = CreateEvent(0,FALSE,FALSE,0);
bCall(boost::bind(&bar, evt));
WaitForSingleObject(evt,INFINITE);
CloseHandle(evt);
}
void bar(HANDLE evt)
{
doSomething();
SetEvent(evt);
}
我查看了 boost::thread 库,但它似乎没有执行此操作的任何东西,我可以看到的关闭是 boost::condition_variable,但它似乎是与互斥锁结合使用的意思,即不是这里的情况.
I looked at the boost::thread library, but it didnt seem to have anything that does this, the closes I could see was the boost::condition_variable, but it appears that is means in conjunction with a mutex, which is not the case here.
推荐答案
我认为一个好的、跨平台的等价于 win32 事件的是 boost::condition,因此您的代码可能如下所示:
I think a good, cross-platform equivalent to win32 events is boost::condition, so your code could look something like this:
void foo()
{
boost::mutex mtxWait;
boost::condition cndSignal;
bCall(boost::bind(&bar, mtxWait, cndSignal));
boost::mutex::scoped_lock mtxWaitLock(mtxWait);
cndSignal.wait(mtxWait); // you could also use cndSignal.timed_wait() here
}
void bar(boost::mutex& mtxWait, boost::condition& cndSignal)
{
doSomething();
cndSignal.notify_one();
}
这篇关于跨平台等价于windows事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:跨平台等价于windows事件
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
