1#include <iostream>
2#include <map>
3#include <string>
4#include <chrono>
5#include <thread>
6#include <mutex>
7
8std::map<std::string, std::string> g_pages;
9std::mutex g_pages_mutex;
10
11void 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
21int 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}