POSIX Thread Termination confusion
Hi,
I have a question about POSIX threads.
Here is my program:
/******************************************************************/
/* Alert: link to the pthreads library by appending
-lpthread to the compile statement */
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h> /* for sleep */
#include <stdlib.h> /* for malloc */
#define NUM_THREADS 5
void *sleeping(void *); /* thread routine */
pthread_t tid[NUM_THREADS]; /* array of thread IDs */
int main()
{
int *sleeptime, i, retval;
for ( i = 0; i < NUM_THREADS; i++) {
sleeptime = (int *)malloc(sizeof(int));
*sleeptime = (i+1)*2;
retval =pthread_create(&tid[i], NULL, sleeping, (void *)sleeptime);
if (retval != 0) {
perror("Error, could not create thread");
}
}
for ( i = 0; i < NUM_THREADS; i++)
{
printf("joining %d\n", i);
pthread_join(tid[i], NULL);
}
printf("main() reporting that all %d threads have terminated\n", i);
return (0);
} /* main */
void *sleeping(void *arg)
{
int sleep_time = *(int *)arg;
printf("thread %d sleeping %d seconds ...\n", pthread_self(), sleep_time);
sleep(sleep_time);
printf("\nthread %d awakening\n", pthread_self());
pthread_exit(NULL);
// return (NULL);
}
/******************************************************************/
Here's the output:
$ ./test
thread 168100320 sleeping 2 seconds ...
thread 168100472 sleeping 4 seconds ...
thread 168101688 sleeping 6 seconds ...
thread 168101840 sleeping 8 seconds ...
joining 0
thread 168101992 sleeping 10 seconds ...
thread 168100320 awakening
$
/******************************************************************/
Now here's my question:
Why doesn't every single thread prints the "awakening" statement? I notice once one thread terminates or exits, all other threads go on business as usual but all the printf statements stop working in other threads. The reason I need these statements is to know what's going on inside each thread.
I would really appreciate it if someone can shed some light on this.
Regards,
Michelle
|