Advertisement
peterzig

C++ Mutex

Nov 16th, 2019
198
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.78 KB | None | 0 0
  1. #include <iostream>
  2. #include <map>
  3. #include <string>
  4. #include <chrono>
  5. #include <thread>
  6. #include <mutex>
  7.  
  8. std::map<std::string, std::string> g_pages;
  9. std::mutex g_pages_mutex;
  10.  
  11. void save_page(const std::string &url)
  12. {
  13.     // simulate a long page fetch
  14.     std::this_thread::sleep_for(std::chrono::seconds(2));
  15.     std::string result = "fake content";
  16.  
  17.     std::lock_guard<std::mutex> guard(g_pages_mutex);
  18.     g_pages[url] = result;
  19. }
  20.  
  21. int main()
  22. {
  23.     std::thread t1(save_page, "http://foo");
  24.     std::thread t2(save_page, "http://bar");
  25.     t1.join();
  26.     t2.join();
  27.  
  28.     // safe to access g_pages without lock now, as the threads are joined
  29.     for (const auto &pair : g_pages) {
  30.         std::cout << pair.first << " => " << pair.second << '\n';
  31.     }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement