Facebook
From Fabix, 3 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 150
  1. #include<iostream>
  2. #include<vector>
  3. #include<queue>
  4. #include<thread>
  5. #include<random>
  6. #include<mutex>
  7. #include<condition_variable>
  8.  
  9. using namespace std;
  10.  
  11. int state = 0;
  12. condition_variable cv;
  13. mutex cv_mtx;
  14.  
  15. double read_sensor(int id) {
  16.         static thread_local std::mt19937 generator(id);
  17.         std::uniform_int_distribution<int> sleep_distribution(100, (id + 1) * 1000);
  18.         std::uniform_real_distribution<double> value_distribution(id, id + 0.99);
  19.         std::this_thread::sleep_for(std::chrono::milliseconds(sleep_distribution(generator)));
  20.         return value_distribution(generator);
  21. }
  22.  
  23.        
  24.  
  25. int main() {
  26.         vector<thread> threads_vec;
  27.         queue<pair<int,double>> sensorsData;
  28.        
  29.  
  30.         int numberOfSensors;
  31.         cin >> numberOfSensors;
  32.  
  33.         unique_lock<mutex> lock(cv_mtx);
  34.  
  35.         for (int i = 0; i < numberOfSensors; i++)
  36.         {
  37.                 thread tmp([&sensorsData , i]() {
  38.                         while (1)
  39.                         {
  40.                                 unique_lock<mutex> lock(cv_mtx);
  41.                                 sensorsData.push(read_sensor(i));
  42.                                 cout << "sensor state" << state << endl;
  43.                                 cout.flush();
  44.                                 state++;
  45.                                 cv.notify_all();
  46.                         }
  47.                        
  48.                 });
  49.                 threads_vec.push_back(move(tmp));
  50.         }      
  51.  
  52.                
  53.         while (state != 5) {
  54.  
  55.        
  56.                         cout << "New data!: ";
  57.                         cv.wait(lock);
  58.                         cout << sensorsData.front() << endl;
  59.                         sensorsData.pop();
  60.                 }
  61.                 state = 0;
  62.        
  63.        
  64.  
  65.  
  66.         for (auto &t : threads_vec)
  67.         {
  68.                 t.join();
  69.         }
  70.         system("pause");
  71.         return 0;
  72. }