Advertisement
Guest User

Untitled

a guest
Mar 27th, 2017
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #include <iostream>
  2. #include <queue>
  3. #include <vector>
  4. #include <thread>
  5. #include <mutex>
  6. #include <condition_variable>
  7.  
  8. #define NUMBER_OF_THREADS 5
  9. #define MAX_QUEUE_ELEM 500
  10.  
  11. std::mutex m;
  12. std::condition_variable producerMutex;
  13. std::condition_variable consumerMutex[NUMBER_OF_THREADS];
  14. std::queue<int> Q;
  15. static int elemCounter = 1;
  16. static int threadCounter = 1;
  17.  
  18. void producer()
  19. {
  20. while (true)
  21. {
  22. // lock thread
  23. std::unique_lock<std::mutex> lock(m);
  24.  
  25. while (Q.size() == MAX_QUEUE_ELEM)
  26. {
  27. std::cout << "Producer waiting" << std::endl;
  28. producerMutex.wait(lock);
  29. }
  30.  
  31. Q.push(elemCounter++);
  32.  
  33. // unlock thread
  34. lock.unlock();
  35.  
  36. // notify next waiting consumer thread
  37. consumerMutex[threadCounter].notify_one();
  38. }
  39. }
  40.  
  41. void consumer()
  42. {
  43. while (true)
  44. {
  45. //lock thread
  46. std::unique_lock<std::mutex> lock(m);
  47.  
  48. while (Q.empty())
  49. {
  50. std::cout << "Consumer waiting : "<< threadCounter << std::endl;
  51. consumerMutex[threadCounter].wait(lock);
  52. }
  53.  
  54. int val = Q.front();
  55. Q.pop();
  56.  
  57. // Printing in lock to print in sequnce
  58. std::cout << "val: " << val << " , thread number: " << threadCounter << std::endl;
  59.  
  60. // unloack thread
  61. lock.unlock();
  62.  
  63. // Notify to next waiting thread in sequnce
  64. if (threadCounter == NUMBER_OF_THREADS)
  65. {
  66. // it means this is last thread so notify first thread
  67. threadCounter = 1;
  68. consumerMutex[threadCounter].notify_one();
  69. }
  70. else
  71. {
  72. consumerMutex[++threadCounter].notify_one();
  73. }
  74. }
  75. }
  76.  
  77. int main()
  78. {
  79. std::thread thrds[NUMBER_OF_THREADS];
  80.  
  81. for (int i = 0; i < NUMBER_OF_THREADS; i++)
  82. {
  83. thrds[i] = std::thread(consumer);
  84. }
  85.  
  86. producer();
  87.  
  88. for (int i = 0; i < NUMBER_OF_THREADS; i++)
  89. {
  90. thrds[i].join();
  91. }
  92.  
  93. return 0;
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement