#include #include #include #include #include #include #include #include sem_t mutex; int count = 0; void * ThreadAdd(void * a) { int i=10, tmp; while(1){ printf("this is in the thread %d and i is %d \n" ,count,i); sem_wait(&mutex); } } int main(int argc, char * argv[]) { pthread_t tid1, tid2; sem_init(&mutex, 0, 1); int i=10; if(pthread_create(&tid1, NULL, ThreadAdd, NULL)){ printf("\n ERROR creating thread 1"); exit(1); } while (1){ printf("Enter the id please \n"); scanf("%d",&count); sem_post(&mutex); } if(pthread_join(tid1,NULL)){ printf("\n ERROR joining thread"); exit(1); } pthread_exit(NULL); } output ------ Enter the id please this is in the thread 0 and i is 10 this is in the thread 0 and i is 10 1 Enter the id please this is in the thread 1 and i is 10 2 Enter the id please this is in the thread 2 and i is 10 3 Enter the id please this is in the thread 3 and i is 10 4 Enter the id please this is in the thread 4 and i is 10 5 Enter the id please this is in the thread 5 and i is 10 6 this is in the thread 6 and i is 10 Enter the id please ______________________________________________ my doubt is even though we have sem_wait in the thread function still why does it executes two times it has to execute one time and then it has to wait so why is it executing two times ?