Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //============================================================================
- // Name : playground.cpp
- // Author :
- // Version :
- // Copyright : Your copyright notice
- // Description : Hello World in C++, Ansi-style
- //============================================================================
- #include <iostream>
- #include <vector>
- #include <map>
- #include <thread>
- #include <chrono>
- #include <cstdlib>
- #include <ctime>
- #include <pthread.h>
- #include <mutex>
- using namespace std;
- std::map<int, int> s_settings;
- mutex s_isCancel;
- mutex map_lock;
- int GetKey() { return rand() % 100; }
- int GetValue() { return rand(); }
- void GenerateSettingsThread() {
- do {
- if (map_lock.try_lock()) {
- for (int i = 0; i < 15; ++i)
- s_settings.erase(GetKey());
- for (int i = 0; i < 40; ++i)
- s_settings[GetKey()] = GetValue();
- map_lock.unlock();
- std::this_thread::sleep_for(std::chrono::milliseconds((rand() % 1000) * 10));
- }
- } while(!s_isCancel.try_lock());
- // because try_lock() locks the mutex
- s_isCancel.unlock();
- return;
- }
- void RequestSettingsThread() {
- while (!s_isCancel.try_lock()) {
- if (map_lock.try_lock()) {
- auto iter = s_settings.find(GetKey());
- if (iter != s_settings.end()) {
- cout << iter->second << endl;
- //std::cout << iter << std::endl;
- }
- map_lock.unlock();
- std::this_thread::sleep_for(std::chrono::milliseconds(10));
- }
- }
- // because try_lock() locks the mutex
- s_isCancel.unlock();
- return;
- }
- int main() {
- s_isCancel.lock();
- map_lock.unlock();
- thread t1(&GenerateSettingsThread);
- thread t2(&RequestSettingsThread);
- std::this_thread::sleep_for(std::chrono::milliseconds(30 * 1000));
- s_isCancel.unlock();
- t1.join();
- t2.join();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement