I am trying to implement very simple Windows events on Linux. Only for my scenario - 3 threads, 1 primary and 2 secondary. Each of the secondary threads raises 1 event by SetEvent, and the main thread expects it. Example:
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)
So, to implement it, I use conditional variables. But my question is the right way? Or am I doing something wrong? My implementation:
// 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);
And everything seems good, but I think this problem will appear when I call the WaitFor .. function in the main thread before SetEvent is called in the secondary thread. On Windows, this worked well, but on Linux - only the idea is described above.
Maybe you can tell me how best to solve this? Thanks.
UPD: The timeout is very important because one of the secondary threads cannot pass SetEvent ().