Cross-Platform equivalent to windows events Cross-Platform equivalent to windows events windows windows

Cross-Platform equivalent to windows events


All these answers are too complex, come on people it isn't that hard.

namespace porting{   class Event;   typedef Event* Event_handle;   static const unsigned k_INFINITE = 0xFFFFFFFF;   class Event   {      friend Event_handle CreateEvent( void );      friend void CloseHandle( Event_handle evt );      friend void SetEvent( Event_handle evt );      friend void WaitForSingleObject( Event_handle evt, unsigned timeout );      Event( void ) : m_bool(false) { }      bool m_bool;      boost::mutex m_mutex;      boost::condition m_condition;   };   Event_handle CreateEvent( void )   { return new Event; }   void CloseHandle( Event_handle evt )   { delete evt; }   void SetEvent( Event_handle evt )   {      evt->m_bool = true;      evt->m_cond.notify_all();   }   void WaitForSingleObject( Event_handle evt, unsigned timeout )   {      boost::scoped_lock lock( evt->m_mutex );      if( timeout == k_INFINITE )      {         while( !evt->m_bool )         {            evt->m_cond.wait( lock );         }      }      else      {         //slightly more complex code for timeouts      }   }}// portingvoid foo(){   porting::Event_handle evt = porting::CreateEvent();   bCall( boost::bind(&bar, evt ) );   porting::WaitForSingleObject( evt, porting::k_INFINITE );   porting::CloseHandle(evt);}void bar( porting::Event_handle evt ){   doSomething();   porting::SetEvent(evt);}

There is probably a bit more to do to get this fully working as I'm not familiar with the semantics of WaitForSingleObject (what happens if two threads call it at the same time, what happens if the same thread calls it twice). However, the solution will look very much like this.


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();}


You could use a promise and a future, from boost thread:

#include <boost\thread.hpp>boost::promise<bool> prom;void foo(){    auto future = prom.get_future();    auto result = future.wait_for(boost::chrono::milliseconds(1000));    // we get here if (a) 1 second passes or (b) bar sets the promise value    if (result==boost::future_status::ready)     {         /* bar set the promise value */     }    if (result==boost::future_status::timeout)    {        /* 1 second passed without bar setting promise value */     }}void bar(){    prom.set_value(true);}