Advertisement
Guest User

VisionLabs test

a guest
Mar 23rd, 2018
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.65 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4. #include <thread>
  5. #include <chrono>
  6. #include <cstdlib>
  7. #include <ctime>
  8. #include <pthread.h>
  9. #include <mutex>
  10.  
  11. using namespace std;
  12.  
  13. std::map<int, int> s_settings;
  14. mutex s_isCancel;
  15. mutex map_lock;
  16.  
  17. int GetKey() { return rand() % 100; }
  18. int GetValue() { return rand(); }
  19.  
  20. void GenerateSettingsThread() {
  21.  
  22.     do {
  23.         if (map_lock.try_lock()) {
  24.             for (int i = 0; i < 15; ++i)
  25.             s_settings.erase(GetKey());
  26.  
  27.             for (int i = 0; i < 40; ++i)
  28.             s_settings[GetKey()] = GetValue();
  29.             map_lock.unlock();
  30.             std::this_thread::sleep_for(std::chrono::milliseconds((rand() % 1000) * 10));
  31.         }
  32.     } while(!s_isCancel.try_lock());
  33.     // because try_lock() locks the mutex
  34.     s_isCancel.unlock();
  35.     return;
  36. }
  37.  
  38. void RequestSettingsThread() {
  39.  
  40.     while (!s_isCancel.try_lock()) {
  41.         if (map_lock.try_lock()) {
  42.             auto iter = s_settings.find(GetKey());
  43.             if (iter != s_settings.end()) {
  44.                 cout << iter->second << endl;
  45.                 //std::cout << iter << std::endl;
  46.             }
  47.             map_lock.unlock();
  48.             std::this_thread::sleep_for(std::chrono::milliseconds(10));
  49.         }
  50.     }
  51.     // because try_lock() locks the mutex
  52.     s_isCancel.unlock();
  53.     return;
  54. }
  55.  
  56. int main() {
  57.  
  58.     s_isCancel.lock();
  59.     map_lock.unlock();
  60.     thread t1(&GenerateSettingsThread);
  61.     thread t2(&RequestSettingsThread);
  62.  
  63.     std::this_thread::sleep_for(std::chrono::milliseconds(30 * 1000));
  64.     s_isCancel.unlock();
  65.     t1.join();
  66.     t2.join();
  67.     return 0;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement