1 /********************************************************
2 * An example source module to accompany...
4 * "Using POSIX Threads: Programming with Pthreads"
5 * by Brad nichols, Dick Buttlar, Jackie Farrell
6 * O'Reilly & Associates, Inc.
8 ********************************************************
11 * An example of using the pthreads_once() call to execute an
12 * initialization procedure.
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
19 * The program's main thread synchronizes its exit with the
20 * exit of the threads using the pthread_join() operation.
27 #include <sys/types.h>
31 #define NUM_THREADS 10
33 static pthread_once_t welcome_once_block
= PTHREAD_ONCE_INIT
;
37 printf("welcome: Welcome\n");
40 void *identify_yourself(void *arg
)
44 if ((rtn
= pthread_once(&welcome_once_block
,
46 fprintf(stderr
, "pthread_once failed with %d",rtn
);
47 pthread_exit((void *)NULL
);
49 printf("identify_yourself: Hi, I'm a thread\n");
56 int *id_arg
, thread_num
, rtn
;
57 pthread_t threads
[NUM_THREADS
];
59 id_arg
= (int *)malloc(NUM_THREADS
*sizeof(int));
61 for (thread_num
= 0; thread_num
< NUM_THREADS
; (thread_num
)++) {
63 id_arg
[thread_num
] = thread_num
;
65 if (( rtn
= pthread_create(&threads
[thread_num
],
68 (void *) &(id_arg
[thread_num
])))
70 fprintf(stderr
, "pthread_create failed with %d",rtn
);
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);
79 printf("main: Goodbye\n");