I have written a small class for synchronizing threads of both Linux (actually Android) and Windows.
Here is the Win32 implementation of my interface :
class SyncObjectWin32 : public SyncObject
{
private:
const HANDLE m_hEvent;
public:
SyncObjectWin32()
: m_hEvent( ::CreateEvent( NULL, FALSE, FALSE ) )
{
if( NULL == m_hEvent )
throw core::Exception( "sys::SyncObjectWin32::SyncObjectWin32() - Failed to create event." );
}
~SyncObjectWin32()
{
::CloseHandle( m_hEvent );
}
void WaitForSignal()
{
::WaitForSingleObject( m_hEvent );
}
void Signal()
{
::SetEvent( m_hEvent );
}
};
The problem is that i'm not sure what would be the POSIX equivalent. So far i've written the following class, based on this SO question, but since the answer is incomplete i'm not sure about how to finish my class :
class SyncObjectPosix
{
private:
pthread_mutex_t m_oMutex;
public:
SyncObjectPosix()
{
pthread_mutex_lock( m_oMutex ); // lock mutex
bool & signalled = find_signal( condition ); // find predicate
signalled = true; // set predicate
pthread_mutex_unlock( m_oMutex ); // unlock mutex
pthread_cond_signal( condition ); // signal condition variable
}
~SyncObjectPosix()
{
}
void WaitForSignal()
{
pthread_mutex_lock(mutex); // lock mutex
bool & signalled = find_signal( condition ); // find predicate
while (!signalled)
{
pthread_cond_timedwait(condition, m_oMutex, timeout);
}
signalled = false; // reset predicate
pthread_mutex_unlock( m_oMutex ); // unlock mutex
}
void Signal()
{
}
};
Signal()
. – LamdinSetEvent()
andWaitForSingleObject()
, a semaphore would also work. See man7.org/linux/man-pages/man3/sem_post.3.html and man7.org/linux/man-pages/man3/sem_wait.3.html There's some good example code on thesem_wait()
man page. – Egalitarianpthread_cond_t
. If you don't want to wait with timeout, there'spthread_cond_wait()
. There's no significant delay in waking a thread waiting on a condition variable, as long as it is able to re-acquire the mutex. I'm not sure what the implementation offind_signal()
is supposed to be - you could/should just makebool signalled
another class private variable. – Lamdin7.14 Signal handling <signal.h>
. POSIX adds further signal-handling (like better specifiedsigaction()
to replacesignal()
, andkill()
ing other processes rather than onlyraise()
ing a signal for the process itself. – Loringpthread_cond_wait()
is allowed to wake up without having been signalled ("spurious wakeup"), and because otherwise if you signalled it before waiting, it would potentially wait forever (apthread_cond_signal()
with no waiting thread is "lost"). – Lamdin