我写了一个小类来同步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() { } };
您所描述的POSIX等效项是POSIX条件变量。请注意,条件变量必须始终与POSIX互斥锁配对使用,但是很多情况下,多个条件变量使用同一互斥锁,因此,如果您不打算将互斥锁专门用于条件变量,则不应将其放置在班级。在您的情况下,Win32和POSIX API之间的含义映射应为:
CreateEvent -> pthread_cond_init
CreateEvent
pthread_cond_init
CloseHandle -> pthread_cond_destroy
CloseHandle
pthread_cond_destroy
WaitForSingleObject-> pthread_cond_wait或pthread_cond_timedwait
WaitForSingleObject
pthread_cond_wait
pthread_cond_timedwait
SetEvent-> pthread_cond_signal或pthread_cond_broadcast
SetEvent
pthread_cond_signal
pthread_cond_broadcast
幸运的是,尽管我建议使用基本的POSIX线程编程,但是有很多关于此的文档。