User:Kr/exit race.c

From Apache OpenOffice Wiki
< User:Kr
Revision as of 10:52, 29 August 2007 by Kr (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

A race between threads and the "exit" call ...

[cpp] /*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
  • /
  1. include <pthread.h>
  2. include <stdio.h>
  3. include <stdlib.h>
  4. include <unistd.h>
  1. ifdef __PRETTY_FUNCTION__
  2. define PFUN __PRETTY_FUNCTION__
  3. else
  4. define PFUN __func__
  5. endif


static void * foo(void * gr) {

   fprintf(stderr, "%s - tid: %x\n", PFUN, pthread_self());
   sleep(5);
   exit(0);

}

static volatile int ad = 0;

  1. ifdef __GNUC__

static void bar(void) __attribute__((destructor));

  1. 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

}

  1. ifdef __SUNPRO_C
  2. pragma fini(bar)
  3. 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);

}

Personal tools