This code sample is based on Michael Burr's answer in How can I wait for any/all pthreads to complete?.
I tried to modify the solution to rely on waitid, instead.
The documentation says that linux's waitid should accept a __WALL
flag which should make it wait on thread children too, but I'm getting errors with it (EINVAL):
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <time.h>
#include <errno.h>
#include <unistd.h>
static
void msleep(int ms)
{
struct timespec waittime;
waittime.tv_sec = (ms / 1000);
ms = ms % 1000;
waittime.tv_nsec = ms * 1000 * 1000;
nanosleep( &waittime, NULL);
}
void* threadfunc( void* c)
{
int id = (int) c;
int i = 0;
for (i = 0 ; i < 12; ++i) {
printf( "thread %d, iteration %d\n", id, i);
msleep(10);
}
return 0;
}
int main()
{
int i = 4;
for (; i; --i) {
pthread_t* tcb = malloc( sizeof(*tcb));
pthread_create( tcb, NULL, threadfunc, (void*) i);
}
msleep(40);
int r;
siginfo_t info;
while(0<=(r=waitid(P_ALL, 0, &info, WEXITED|__WALL)) || errno == EINTR)
;
printf("r=%d %m\n", r);
#if 0
pthread_exit(0);
#endif
return 0;
}
Any idea as to why it's not working? If it isn't obvious, I'd like to get the same result as with pthread_exit(0) from main -- all threads should run to completion.