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 eitherlock
ortry_lock
until it callsunlock
. - When a thread owns a
mutex
, all other threads will block (for calls tolock
) or receive a false return value (fortry_lock
) if they attempt to claim ownership of themutex
. - A calling thread must not own the
mutex
prior to callinglock
ortry_lock
.
The behavior of a program is undefined if a mutex
is destroyed while still owned by any threads, or a thread terminates while owning a mutex
. The mutex
class satisfies all requirements of Mutex and StandardLayoutType.
std::mutex
is neither copyable nor movable.
Mutex class is a synchronization primitives can be used to protect shared data from multiple threads access.
Mutex provides exclusive, non-recursive ownership semantics:
From a successful call to lock or unlock try_lock until the call date, the calling thread owns a mutex.
When a thread owns a mutex, if all other threads trying to claim ownership of the mutex, they will block (used to call lock) or receive an error return value (for try_lock).
Before calling lock or try_lock, the calling thread can not own the mutex.
It is destroyed if a mutex is still owned by any thread, or a thread has terminated when a mutex, the behavior of the program is uncertain. Mutex Mutex class and meets all requirements of StandardLayoutType.
std :: mutex neither copied nor moved.
lock:locks the mutex, blocks if the mutex is not available;
Mutex lock, if the mutex is not available, blocking
tries to lock the mutex, returns if the mutex is not available |
Trying to lock a mutex mutex is not available, then returns
unlock unlocks the mutex
native_handle return to baseline achieved native handle object definition
Usually do not directly access the std :: mutex: std :: unique_lock, std :: lock_guard or std :: scoped_lock (starting from C ++ 17) in a more secure way to manage abnormal lock.
Example
This example shows how to use the mutex to protect shared between two threads std :: map.
// threadTest.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#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";
std::lock_guard<std::mutex> guard(g_pages_mutex);
g_pages[url] = result;
}
int main()
{
std::thread t1(save_page, "http://foo");
std::thread t2(save_page, "http://bar");
t1.join();
t2.join();
// safe to access g_pages without lock now, as the threads are joined
for (const auto &pair : g_pages) {
std::cout << pair.first << " => " << pair.second << '\n';
}
return 0;
}