I am new in thread syncronization. I was reading many implementations of conditional variables, like boost::threads and pthread for win32. I just implemented this quite simple monitor with wait/notify/noifyall, and i guess that there are many hidden problems with it, that I would like to discover from more experienced people. Any suggestion?
class ConditionVar
{
public :
ConditionVar () : semaphore ( INVALID_HANDLE_VALUE ) , total_waiters (0)
{
semaphore = ::CreateSemaphoreA ( NULL , 0 /* initial count */ , LONG_MAX /* max count */ , NULL );
}
~ConditionVar ()
{
::CloseHandle ( semaphore ) ;
}
public :
template <class P>
void Wait ( P pred )
{
while ( !pred() ) Wait();
}
public :
void Wait ( void )
{
INTERLOCKED_WRITE_RELEASE(&total_waiters,total_waiters + 1 );
::WaitForSingleObject ( semaphore , INFINITE );
}
//! it will notify one waiter
void Notify ( void )
{
if ( INTERLOCKED_READ_ACQUIRE(&total_waiters) )
{
Wake (1);
}
}
void NotifyAll (void )
{
if ( INTERLOCKED_READ_ACQUIRE(&total_waiters) )
{
std::cout << "notifying " << total_waiters ;
Wake ( total_waiters );
}
}
protected :
void Wake ( int count )
{
INTERLOCKED_WRITE_RELEASE(&total_waiters,total_waiters - count );
::ReleaseSemaphore ( semaphore , count , NULL );
}
private :
HANDLE semaphore;
long total_waiters;
};