Home | History | Annotate | Download | only in tests
      1 /********************************************************
      2  * An example source module to accompany...
      3  *
      4  * "Using POSIX Threads: Programming with Pthreads"
      5  *     by Brad nichols, Dick Buttlar, Jackie Farrell
      6  *     O'Reilly & Associates, Inc.
      7  *
      8  ********************************************************
      9  * once_exam.c
     10  *
     11  * An example of using the pthreads_once() call to execute an
     12  * initialization procedure.
     13  *
     14  * A program spawns multiple threads and each one tries to
     15  * execute the routine welcome() using the once call. Only
     16  * the first thread into the once routine will actually
     17  * execute welcome().
     18  *
     19  * The program's main thread synchronizes its exit with the
     20  * exit of the threads using the pthread_join() operation.
     21  *
     22 */
     23 
     24 #include <stdlib.h>
     25 #include <stdio.h>
     26 #include <unistd.h>
     27 #include <sys/types.h>
     28 
     29 #include <pthread.h>
     30 
     31 #define  NUM_THREADS   10
     32 
     33 static pthread_once_t welcome_once_block = PTHREAD_ONCE_INIT;
     34 
     35 void welcome(void)
     36 {
     37 	printf("welcome: Welcome\n");
     38 }
     39 
     40 void *identify_yourself(void *arg)
     41 {
     42 	int rtn;
     43 
     44 	if ((rtn = pthread_once(&welcome_once_block,
     45 			        welcome)) != 0) {
     46 		fprintf(stderr, "pthread_once failed with %d",rtn);
     47 		pthread_exit((void *)NULL);
     48 	}
     49 	printf("identify_yourself: Hi, I'm a thread\n");
     50         return(NULL);
     51 }
     52 
     53 extern int
     54 main(void)
     55 {
     56 	int             *id_arg, thread_num, rtn;
     57 	pthread_t       threads[NUM_THREADS];
     58 
     59 	id_arg = (int *)malloc(NUM_THREADS*sizeof(int));
     60 
     61 	for (thread_num = 0; thread_num < NUM_THREADS; (thread_num)++) {
     62 
     63 		id_arg[thread_num] = thread_num;
     64 
     65 		if (( rtn = pthread_create(&threads[thread_num],
     66 					   NULL,
     67 					   identify_yourself,
     68 					   (void *) &(id_arg[thread_num])))
     69 		    != 0) {
     70 		  fprintf(stderr, "pthread_create failed with %d",rtn);
     71 		  exit(1);
     72 		}
     73 	}
     74 
     75 	for (thread_num = 0; thread_num < NUM_THREADS; thread_num++) {
     76 	  pthread_join(threads[thread_num], NULL);
     77 	  //printf("main: joined to thread %d\n", thread_num);
     78 	}
     79 	printf("main: Goodbye\n");
     80         return 0;
     81 }
     82