fork download
  1. #include<pthread.h>
  2. #include<stdio.h>
  3. int signal;
  4. pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
  5. pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  6. void consumer()
  7. {
  8. pthread_mutex_lock(&mutex);
  9. if(signal==0)
  10. {
  11. printf("It is not my turn let me sleep\n");
  12. pthread_cond_wait(&cond,&mutex);
  13. printf("I got signal to do the work\n");
  14. }
  15. pthread_mutex_unlock(&mutex);
  16. }
  17. void producer()
  18. {
  19. pthread_mutex_lock(&mutex);
  20. printf("Resources locked\n");
  21. signal=1;
  22. if(signal==1)
  23. {
  24. pthread_cond_signal(&cond);
  25. }
  26. pthread_mutex_unlock(&mutex);
  27. }
  28.  
  29. int main()
  30. {
  31. pthread_t t1, t2;
  32. int status1, status2;
  33. status1=pthread_create(&t1, NULL, (void*)consumer, NULL);
  34. status2=pthread_create(&t2, NULL, (void*)producer, NULL);
  35. pthread_join (t1,NULL);
  36. pthread_join (t2, NULL);
  37. return 0;
  38. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
Resources locked