Hi All,
#include <iostream>
#include <map>
#include <string>
#include <chrono>
#include <thread>
#include <mutex>
std::map<std::string, std::string> g_pages;
std::mutex g_pages_mutex;
void save_page(const std::string &url)
{
// simulate a long page fetch
std::this_thread::sleep_for(std::chrono::seconds(2));
std::string result = "fake content";
g_pages_mutex.lock();
g_pages[url] = result;
g_pages_mutex.unlock();
}
int main()
{
std::thread t1(save_page, "
http://foo");
std::thread t2(save_page, "
http://bar");
t1.join();
t2.join();
g_pages_mutex.lock(); // not necessary as the threads are joined, but good style
for (const auto &pair : g_pages) {
std::cout << pair.first << " => " << pair.second << '\n';
}
g_pages_mutex.unlock();
I came across a code like this and they have created mutex variable to g_pages as g_pages_mutex.But I dont understand how this mutex variable is related to g_pages?
we havent provided address of g_pages to g_pages_mutex,then how does mutex variable knows which variable to act on?
Is it like we have to add "_mutex " to create a mutex for a variable?
(eg...if I declare Account Myaccount then I can declare mutex to it by keeping
variable name as Myaccount_mutex)
Is it so?
I am new to c++ ,,,very very new to multithreading.
Thanks in advance