跨平台等价于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();
}

相关文章