0

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.

Petr Skocik
  • 58,047
  • 6
  • 95
  • 142

1 Answers1

0

__WALL cannot be used in waitid().

Based in what I read, __WALL (wait for all children, regardless of clone or non-clone), can be used with only waitpid(), wait3() and wait4().

pevik
  • 4,523
  • 3
  • 33
  • 44
Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34
  • Tried those other ones, but I'm getting ECHILD with them :(. Thanks for the answer. – Petr Skocik May 24 '17 at 18:23
  • ECHILD may also come if you have improper PID specified in waitpid(). Ensure you tried with pid as "-1" , to wait for any child irrespective of process groups. – Pavan Chandaka May 24 '17 at 18:30