Advertisement
cinnamonandrew

Untitled

Oct 26th, 2020
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <condition_variable>
  5. #include <queue>
  6. #include <chrono>
  7.  
  8. #include "stuff.hpp"
  9.  
  10. using namespace std;
  11.  
  12. int LEN = 5;
  13.  
  14. mutex m;
  15. condition_variable read;
  16. condition_variable write;
  17.  
  18. vector<int> a, b;
  19. queue<int> prod;
  20. int sum;
  21.  
  22. bool dataReady = false;
  23. bool haveData = true;
  24.  
  25. void consumer()
  26. {
  27. while(haveData)
  28. {
  29. cout<<"waiting"<<endl;
  30. unique_lock<mutex> lock(m);
  31.  
  32. while(!dataReady)
  33. {
  34. read.wait(lock);
  35. }
  36.  
  37. sum += prod.front();
  38. prod.pop();
  39. dataReady = false;
  40. }
  41. }
  42.  
  43. void producer()
  44. {
  45. for(int i = 0; i < LEN; ++i)
  46. {
  47. this_thread::sleep_for(chrono::milliseconds(500));
  48. lock_guard<mutex> lock(m);
  49.  
  50. prod.push(a[i]*b[i]);
  51.  
  52. cout<<"Prod aXb="<<a[i]<<" x "<<b[i]<<"="<<a[i]*b[i]<<endl;
  53.  
  54. dataReady = true;
  55. read.notify_one();
  56. }
  57.  
  58. lock_guard<mutex> lock(m);
  59. dataReady = true;
  60. haveData = false;
  61. read.notify_one();
  62. }
  63.  
  64. int main()
  65. {
  66. srand ( time(NULL) ); // get real random values
  67.  
  68. a = generate_vector(LEN);
  69. b = generate_vector(LEN);
  70.  
  71. cout<<"Vector a is: ";
  72. for(int i = 0; i < LEN; ++i) { cout<<a[i]<<' '; } cout<<endl;
  73. cout<<"Vector b is: ";
  74. for(int i = 0; i < LEN; ++i) { cout<<b[i]<<' '; } cout<<endl;
  75.  
  76. thread c(consumer);
  77. thread p(producer);
  78.  
  79. p.join();
  80. c.join();
  81.  
  82. cout<<"Scalar product is "<<sum<<endl;
  83.  
  84. return 0;
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement