我试图在Linux中实现非常简单的Windows事件.仅适用于我的场景 – 3个线程,1个主线程和2个辅助线程.每个辅助线程通过SetEvent引发1个事件,主线程等待它.例:
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().
解决方法:
*上也有类似的问题:WaitForSingleObject and WaitForMultipleObjects equivalent in linux
另外你可以使用信号量:
sem_t semOne ;
sem_t semTwo ;
sem_t semMain ;
在主线程中:
sem_init(semOne,0,0) ;
sem_init(semTwo,0,0) ;
sem_init(semMain,0,0) ;
...
sem_wait(&semMain);
// Thread 1
sem_wait(&semOne);
sem_post(&semMain);
// Thread 2
sem_wait(&semTwo);
sem_post(&semMain);
详细说明和各种例子可以在这里找到:—— http://www.ibm.com/developerworks/linux/library/l-ipc2lin3/index.html
之前的链接不再可用. The Internet Archive的Wayback Machine上最新的存档版本是:
https://web.archive.org/web/20130515223326/http://www.ibm.com/developerworks/linux/library/l-ipc2lin3/index.html