User:Kr/exit race.c
From Apache OpenOffice Wiki
< User:Kr
A race between threads and the "exit" call ...
Solaris:
> cc exit_race.c -o exit_race.bin > ./exit_race.bin main - tid: 1 foo - tid: 2 bar - tid: 2 main - ad: 1 Linux: > gcc -g exit_race.c -lpthread > ./exit_race.bin main - tid: b7ddbac0 foo - tid: b7ddab90 bar - tid: b7ddab90 main - ad: 1
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #ifdef __PRETTY_FUNCTION__ # define PFUN __PRETTY_FUNCTION__ #else # define PFUN __func__ #endif static void * foo(void * gr) { fprintf(stderr, "%s - tid: %x\n", PFUN, pthread_self()); sleep(5); exit(0); } static volatile int ad = 0; #ifdef __GNUC__ static void bar(void) __attribute__((destructor)); #endif static void bar(void) { fprintf(stderr, "%s - tid: %x\n", PFUN, pthread_self()); ad = 1; sleep(5); // this just stands for some slow de-initialization } #ifdef __SUNPRO_C # pragma fini(bar) #endif static pthread_t bt; static void main_cleanup(void * gr) { fprintf(stderr, "%s - tid: %x\n", PFUN, pthread_self()); } int main() { fprintf(stderr, "%s - tid: %x\n", PFUN, pthread_self()); pthread_create(&bt, NULL, foo, NULL); while (!ad) ; // Busy wait for ad to change! fprintf(stderr, "%s - ad: %i\n", PFUN, ad); pthread_exit(NULL); }