我写了一个小类来同步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的等价物。 到目前为止,我已根据this SO question撰写了以下课程,但由于答案不完整,我不确定如何完成课程:
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()
{
}
};
答案 0 :(得分:8)
同时检查svn merge -r HEAD:45 yourFile
svn ci yourFile -m "Reverting back to rev 45"
。如果你只需要一个消费者和一个生产者,它似乎几乎相当于eventfd
。
CreateEvent
- > CreateEvent
eventfd
- > CloseHandle
close
- > SetEvent
write
- > WaitForSingleObject
read
- > WaitForMultipleObjects
和select
对应的fd
更多阅读 http://www.sourcexr.com/articles/2013/10/26/lightweight-inter-process-signaling-with-eventfd
答案 1 :(得分:7)
所描述的POSIX等价物是POSIX条件变量。请注意,条件变量必须始终与POSIX互斥锁配对使用,但很多情况下,多个条件变量使用相同的互斥锁,因此如果您不打算将互斥锁专用于条件变量,则不应该使用该变量。把它放在课堂上。在Win32和POSIX API之间的意义映射应该是:
function surveyFunction() {
var div = document.getElementById("list").value;
$.ajax({
type: "POST",
url: "possurv.pl",
data: div,
success: function(result){
$('#survfeedback').html(result);
}
});
}
- > CreateEvent
pthread_cond_init
- > CloseHandle
pthread_cond_destroy
- > WaitForSingleObject
或pthread_cond_wait
pthread_cond_timedwait
- > SetEvent
或pthread_cond_signal
幸运的是,有很多关于此的文档,但我建议使用基本的Programming POSIX Threads。
答案 2 :(得分:2)
代码的pthreads相当于:
class SyncObjectPosix
{
private:
bool signalled;
pthread_mutex_t mutex;
pthread_cond_t cond;
public:
SyncObjectPosix()
{
signalled = false;
pthread_mutex_init(&mutex, NULL);
pthread_cond_init(&cond, NULL);
}
~SyncObjectPosix()
{
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond);
}
void WaitForSignal()
{
pthread_mutex_lock(&mutex);
while (!signalled)
{
pthread_cond_wait(&cond, &mutex);
}
signalled = false;
pthread_mutex_unlock(&mutex);
}
void Signal()
{
pthread_mutex_lock(&mutex);
signalled = true;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}
};
答案 3 :(得分:0)
我们的开源pevents
库仅适用于所有平台。这是非常小的(单个文件)C ++代码,您可以将其添加到现有项目中,并访问基于pthreads同步基元构建的Windows事件api。
最重要的花絮是它支持WaitForMultipleObjects
。