我写了一个小类,用于同步Linux(实际上是Android)和Windows的线程。
这是我的接口的Win32实现:
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 );
}
};
问题在于我不确定POSIX等效的内容是什么。 到目前为止,我已经根据这个SO问题编写了以下类,但由于答案不完整,我不确定如何完成我的类:
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()
中。 - cafSetEvent()
和WaitForSingleObject()
的方式来看,信号量也可以工作。请参见http://man7.org/linux/man-pages/man3/sem_post.3.html和http://man7.org/linux/man-pages/man3/sem_wait.3.html。在`sem_wait()`手册页上有一些很好的示例代码。 - Andrew Henle