std::mutex

From cppreference.com
Defined in header <mutex>
class mutex;
(since C++11)

The mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads.

mutex offers exclusive, non-recursive ownership semantics:

  • A calling thread owns a mutex from the time that it successfully calls either lock or try_lock until it calls unlock.
  • When a thread owns a mutex, all other threads will block (for calls to lock) or receive a false return value (for try_lock) if they attempt to claim ownership of the mutex.
  • A calling thread must not own the mutex prior to calling lock or try_lock.

The behavior of a program is undefined if a mutex is destroyed while still owned by some thread. The mutex class is non-copyable.

Contents

[edit] Member types

Member type Definition
native_handle_type implementation-defined

[edit] Member functions

constructs the mutex
(public member function)
Locking
locks the mutex, blocks if the mutex is not available
(public member function)
tries to lock the mutex, returns if the mutex is not available
(public member function)
unlocks the mutex
(public member function)
Native handle
returns the underlying implementation-defined thread handle
(public member function)

[edit] Example

This example shows how a mutex can be used to protect a std::map shared between two threads.

#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();
}

Output:

http://bar => fake content
http://foo => fake content