Advertisement
Guest User

VisionLabs test

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