#include #include #include #include #include #include #include volatile unsigned lock = 0; __thread unsigned locks = 0; static void * start(void *cookie) { pid_t pid; for (;;) { while (atomic_cas_uint(&lock, 0, 1) != 0) continue; locks++; pid = fork(); if (--locks) errx(1, "lock count"); if (atomic_cas_uint(&lock, 1, 0) != 1) errx(1, "lost lock"); switch (pid) { case -1: /* error */ err(1, "fork"); case 0: /* child */ _exit(0); default: /* parent */ break; } if (wait4(pid, NULL, 0, NULL) == -1) err(1, "wait4"); } } int main(void) { pthread_t t; unsigned n = 100; int error; while (n --> 0) { error = pthread_create(&t, NULL, &start, NULL); if (error) errc(1, error, "pthread_create"); } (void)pthread_join(t, NULL); return 0; }