tags:

views:

99

answers:

2

I have the following Windows code that spawns two threads then waits until they have both completed:

hThreads[0] = _beginthread(&do_a, 0, p_args_a);
hThreads[1] = _beginthread(&do_b, 0, p_args_b);
WaitForMultipleObjects(2, hThreads, TRUE, INFINITE);

I am now porting the same code to use pthreads but am unsure how to do the equivalent of WaitForMultipleObjects:

pthread_create(&hThreads[0], 0, &do_a, p_args_a);
pthread_create(&hThreads[1], 0, &do_b, p_args_b);
???

Is there an equivalent way, using pthreads, to achieve the same functionality?

+1  A: 

If you want to wait for all, as you're doing here, you can simply call pthread_join() for each thread. It will accomplish the same thing.

pthread_create(&hThreads[0], 0, &do_a, p_args_a);
pthread_create(&hThreads[1], 0, &do_b, p_args_b);

pthread_join(hThreads[0], NULL);
pthread_join(hThreads[1], NULL);

You can get fancy and do this in a for loop if you've got more than a couple of threads.

Derek Park
Do I need to call pthread_exit in do_a and do_b?
Ben Lever
Some further reading ... pthread_exit is only really required to pass information back to the pthread_join call waiting for the thread to exit?
Ben Lever
Sorry, I just saw your comment. No, you don't need to call `pthread_exit` unless that it more convenient. It's analogous to calling `exit` from `main`. You can do so if you want, but you can also just return normally, and the effect will be as if you had called `pthread_exit` with the return value from the thread function. I almost never call `pthread_exit`. I also almost never use the return value (hence why I pass NULL as the second arg to `pthread_join`).
Derek Park
A: 

I always just used a for loop with pthread_join

int i;
for(i=0;i<threads;i++)
    pthread_join(tids[i], NULL);
pschorf