Waiting for multiple events in Unix C++

Jan 22, 2015 at 5:35am
Hi,
I am trying to port my multi threaded windows application to Unix. My requirement is to signal a thread with multiple events. In windows i have used "WaitForMultipleEvents()" , but in unix i implemented events with conditional variable. There only "pthread_cond_wait(&cond, &mutex) is available, which will wait for single event to set. But i need my thread to wait for multiple events.Help me to port this in unix.
Jan 22, 2015 at 10:32am
I'm not sure but can't you keep calling pthread_cond_wait until you have received all the events that you are waiting for?
Jan 23, 2015 at 3:54am
Why not populate an event queue with event objects and use the condition variable to signal the thread that there are some events in the queue to be processed? The waking thread can then process the queue until it is empty before sleeping and waiting for the next signal.
Jan 30, 2015 at 6:51pm
Use semaphores.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <thread>
#include <iostream>
#include <unistd.h>
#include <semaphore.h>

using std::cout;
using std::thread;
sem_t sem;

void f1()
{
	sleep(1);
	sem_post(&sem);
	sleep(3);
	sem_post(&sem);
}

void f2()
{
	sleep(2);
	sem_post(&sem);
}

int main()
{
	sem_init(&sem, 0, 0);
	thread t1(f1);
	thread t2(f2);

	for (int i = 0; i < 3; i++) {
		sem_wait(&sem);
		cout << "Event!\n";
	}
	cout << "Exit\n";
}
Topic archived. No new replies allowed.