Following is a program which uses pthreads.
#include <pthread.h> // posix threads
#include <stdio.h>
#include <stdlib.h>
/* to compile use -lpthread */
void * sample_thread(void *);
#define MAX 10
int main()
{
pthread_t tid;
pthread_attr_t attr;
int k;
pthread_attr_init(&attr); // set default attributes
pthread_create(&tid, &attr, sample_thread, NULL); // create new thread
// sample_thread will run as the new thread
for(k=0; k<MAX; k++) {
printf("Hi I'am %s %d \n",__func__,k);
}
//this would kill all the threads,
}
void * sample_thread(void * p)
{
int k;
for(k=0; k<MAX; k++) {
printf("Hi I'am %s %d \n",__func__,k);
}
}
Each time when I run the program I am expecting to get different number of execution numbers from the main thread and the child thread (because the main thread might exit before the child). I am getting this expected output sometimes. But I got an output as follows, which I am unable to understand why.
Hi I'am main 0
Hi I'am main 1
Hi I'am main 2
Hi I'am main 3
Hi I'am main 4
Hi I'am main 5
Hi I'am main 6
Hi I'am main 7
Hi I'am main 8
Hi I'am main 9
Hi I'am sample_thread 0
Hi I'am sample_thread 0
Hi I'am sample_thread 1
Hi I'am sample_thread 2
Hi I'am sample_thread 3
Hi I'am sample_thread 4
Hi I'am sample_thread 4
Hi I'am sample_thread 5
Why did the sample thread 0 and 4 print twice?
exitis required by POSIX to synchronize with stdio operations, but if it failed to do so, there could be data races (and random corruption) when it flushesstdoutsimultaneously with another thread writing tostdout).