fork download
  1. #include <iostream>
  2. #include <string>
  3. #include <mutex>
  4. #include <thread>
  5. #include <chrono>
  6. #include <unordered_map>
  7.  
  8. std::unordered_map<std::string, std::string> map1 ( {{"apple","red"},{"lemon","yellow"}} );
  9. std::mutex mtx1;
  10.  
  11. std::unordered_map<std::string, std::string> map2 ( {{"orange","orange"},{"strawberry","red"}} );
  12. std::mutex mtx2;
  13.  
  14. void func() {
  15. std::lock_guard<std::mutex> lock1(mtx1);
  16. std::lock_guard<std::mutex> lock2(mtx2);
  17.  
  18. std::cout << "map1: ";
  19. for (auto& x: map1) std::cout << " " << x.first << " => " << x.second << ", ";
  20. std::cout << std::endl << "map2: ";
  21. for (auto& x: map2) std::cout << " " << x.first << " => " << x.second << ", ";
  22. std::cout << std::endl << std::endl;
  23.  
  24. auto it1 = map1.find("apple");
  25. if(it1 != map1.end()) {
  26. auto val = *it1;
  27. map1.erase(it1);
  28. std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(1000));
  29. map2[val.first] = val.second;
  30. }
  31. }
  32.  
  33. int main ()
  34. {
  35. std::thread t1(func);
  36. std::this_thread::sleep_for(std::chrono::duration<double, std::milli>(500));
  37. std::thread t2(func);
  38. t1.join();
  39. t2.join();
  40.  
  41. return 0;
  42. }
Success #stdin #stdout 0s 20880KB
stdin
Standard input is empty
stdout
map1:  lemon => yellow,  apple => red, 
map2:  strawberry => red,  orange => orange, 

map1:  lemon => yellow, 
map2:  apple => red,  strawberry => red,  orange => orange,