Mutex syntax

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
The mutex g_pages_mutex is used to serialse write access to g_pages.
Last edited on
RAII.

1
2
3
4
5
6
7
8
9
10
void save_page(const std::string &url)
{
    // ...

    g_pages_mutex.lock();

    g_pages[url] = result; // *** what would happen if this throws?

    g_pages_mutex.unlock();
}


1
2
3
4
5
6
7
8
void save_page(const std::string &url)
{
    // ...

    std::lock_guard<std::mutex> lock( g_pages_mutex );

    g_pages[url] = result; // our code is exception-safe
}


yes, that example (the OP code was from http://en.cppreference.com/w/cpp/thread/mutex ) has always bugged me, edited to mention lock_guard
Topic archived. No new replies allowed.