User:Kr/A Thread's Life/Example Code

From Apache OpenOffice Wiki
< User:Kr‎ | A Thread's Life
Revision as of 08:20, 4 September 2007 by Kr (Talk | contribs)

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

[cpp]

  1. include <stdlib.h>
  2. include <stdio.h>
  3. include <pthread.h>


static void * holder(void * gr) {

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


   if (1) // This may only be true if this is the last "holder" thread!
       exit(0);
   else
       pthread_exit(NULL);

}

static void createHolderThread() {

   pthread_attr_t attr;
   
   pthread_attr_init(&attr);
   pthread_attr_setdetachstate(&attr, 1);
   
   pthread_t bt;
   pthread_create(&bt, &attr, holder, NULL);
   pthread_attr_destroy(&attr);

}


static void * holded(void * gr) {

   fprintf(stderr, "%s - tid: %x\n", __PRETTY_FUNCTION__, pthread_self());
   sleep(10);
   pthread_exit(NULL);

}

static pthread_t hd;

static void join_holded(void) {

   fprintf(stderr, "%s - tid: %x\n", __PRETTY_FUNCTION__, pthread_self());
   // You may want to cancel a thread actively during termination:
   pthread_cancel(hd);
   // respectively
   //pthread_kill();
   pthread_join(hd, NULL);

}

static void createHoldedThread(void) {

   pthread_create(&hd, NULL, holded, NULL);
   atexit(join_holded);

}


static void print_something(void) {

   fprintf(stderr, "%s - printing ... tid: %x\n", __PRETTY_FUNCTION__, pthread_self());

}

int main(void) {

   atexit(print_something);
   createHolderThread();
   createHoldedThread();
   pthread_exit(NULL);
   return 0;

}

Personal tools