我想在Linux中實現非常簡單的Windows事件。僅適用於我的場景 - 3個線程,1個主要和2個輔助。每個輔助線程通過SetEvent引發1個事件,主線程等待它。例如:使用條件變量在Linux中執行Windows事件?
int main()
{
void* Events[2];
Events[0] = CreateEvent();
Events[1] = CreateEvent();
pthread_start(Thread, Events[0]);
pthread_start(Thread, Events[1]);
WaitForMultipleObjects(2, Events, 30000) // 30 seconds timeout
return 0;
}
int* thread(void* Event)
{
// Do something
SetEvent(Event);
// Do something
}
所以,要實現它,我使用條件變量。但我的問題是 - 這是一種正確的方式嗎?或者我做錯了什麼?我的實現:
// Actually, this function return pointer to struct with mutex and cond
// here i just simplified example
void* CreateEvent(mutex, condition)
{
pthread_mutex_init(mutex, NULL);
pthread_cond_init(condition, NULL);
}
bool SetEvent (mutex, condition)
{
pthread_mutex_lock(mutex);
pthread_cond_signal(condition);
pthread_mutex_unlock(mutex);
}
int WaitForSingleObject(mutex, condition, timeout)
{
pthread_mutex_lock(mutex);
pthread_cond_timedwait(condition, mutex, timeout);
pthread_mutex_unlock(mutex);
}
// Call WaitForSingleObject for each event.
// Yes, i know, that its a wrong way, but it should work in my example.
int WaitForMultipleObjects(count, mutex[], condition[], timeout);
而且一切似乎不錯,但我認爲,當我打電話WaitFor的..在輔助線程SetEvent的前主線程函數會被這個問題就會出現。在Windows中,它運行良好,但在Linux中 - 只有想法如上所述。
也許你告訴我解決問題的更好方法?謝謝。
UPD:超時非常重要,因爲其中一個輔助線程可能無法通過SetEvent()。
我們有一個開源的(MIT授權)庫,名爲'pevents',它在linux上實現了WIN32手動和自動重置事件,幷包含WaitForSingleObject和WaitForMultipleObjects克隆:https://github.com/NeoSmart/PEvents –
可能重複的[pthread-like windows手動重置事件](http://stackoverflow.com/questions/178114/pthread-like-windows-manual-reset-event) – jww