fork download
  1. #include<bits/stdc++.h>
  2. #include<mutex>
  3. #include<thread>
  4. using namespace std;
  5. mutex m;
  6. condition_variable cv;
  7. int fll=0;
  8. int empty=0;
  9. // using namespace std;
  10. void producer(int i){
  11. unique_lock<mutex>lock(m);
  12. while(empty==0){
  13. cv.wait(lock);
  14. }
  15. cout<<"producer "<<i<<" has produced"<<'\n';
  16. empty--;
  17. fll++;
  18. cv.notify_all();
  19.  
  20. }
  21. void consumer(int i){
  22. unique_lock<mutex>lock(m);
  23. while(fll==0){
  24. cv.wait(lock);
  25. }
  26. cout<<"consumer "<<i<<" has consumed"<<'\n';
  27. empty++;
  28. fll--;
  29. cv.notify_all();
  30. }
  31. int main(){
  32. fll=0;
  33. empty=5;
  34. thread t1(consumer,1);
  35. thread t2(consumer,2);
  36. thread t3(consumer,3);
  37. thread t4(consumer,4);
  38. thread t5(consumer,5);
  39. thread t6(consumer,6);
  40. thread t7(consumer,7);
  41. thread t8(producer,1);
  42. thread t9(producer,2);
  43. thread t10(producer,3);
  44. thread t11(producer,4);
  45. thread t12(producer,5);
  46. thread t13(producer,6);
  47. thread t14(producer,7);
  48. // thread t15(producer,8);
  49. thread t16(producer,9);
  50. t1.join();
  51. t2.join();
  52. t3.join();
  53. t4.join();
  54. t5.join();
  55. t6.join();
  56. t7.join();
  57. t8.join();
  58. t9.join();
  59. t10.join();
  60. t11.join();
  61. t12.join();
  62. t13.join();
  63. t14.join();
  64. // t15.join();
  65. t16.join();
  66. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
producer 1 has produced
consumer 7 has consumed
producer 2 has produced
producer 3 has produced
producer 4 has produced
producer 5 has produced
producer 6 has produced
consumer 6 has consumed
producer 7 has produced
consumer 5 has consumed
producer 9 has produced
consumer 4 has consumed
consumer 3 has consumed
consumer 2 has consumed
consumer 1 has consumed