Start several threads

suggest change

<threads.h> is optional. An implementation that does not provide it defines __STDC_NO_THREADS__ as 1. The C standard does not require printf to be free of data races; this example uses it only to show that each thread received its own argument.

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>

struct my_thread_data {
   double factor;
};

int my_thread_func(void *a) {
   struct my_thread_data *d = a;
   printf("we found %g\n", d->factor);
   return d->factor > 1.0;
}

int main(int argc, char *argv[]) {
    unsigned long long requested = 4;
    unsigned n;
    unsigned i;
    unsigned started = 0;

    if (argc > 1) {
        char *end = NULL;
        errno = 0;
        requested = strtoull(argv[1], &end, 0);
        if (argv[1] == end || *end != '\0' || errno == ERANGE
            || requested == 0 || requested > 64)
            return EXIT_FAILURE;
    }
    n = (unsigned)requested;

    /* A VLA cannot have an initializer. */
    struct my_thread_data D[n];
    thrd_t id[n];

    for (i = 0; i < n; ++i)
        D[i] = (struct my_thread_data){ .factor = 0.5 * i };

    for (i = 0; i < n; ++i) {
        if (thrd_create(&id[i], my_thread_func, &D[i]) != thrd_success)
            break;
        ++started;
    }

    /* Join only threads that were created. Discard their status. */
    for (i = 0; i < started; ++i)
        thrd_join(id[i], NULL);

    return started == n ? EXIT_SUCCESS : EXIT_FAILURE;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents