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.
互斥体类是一个同步原语,可用于保护共享数据免受多个线程同时访问。
互斥锁提供排他的,非递归的所有权语义:
从成功调用锁或try_lock直到调用解锁为止,调用线程拥有一个互斥量。
当一个线程拥有一个互斥锁时,如果所有其他线程试图声明该互斥锁的所有权,它们将阻塞(用于调用锁)或接收到错误的返回值(对于try_lock)。
在调用lock或try_lock之前,调用线程不得拥有互斥量。
如果一个互斥锁仍然由任何线程拥有时被销毁,或者一个线程在拥有一个互斥锁时终止,则程序的行为是不确定的。 互斥锁类满足Mutex和StandardLayoutType的所有要求。
std :: mutex既不可复制也不可移动。
lock:locks the mutex, blocks if the mutex is not available;
锁定互斥锁,如果互斥锁不可用,则阻塞
tries to lock the mutex, returns if the mutex is not available |
尝试锁定互斥锁,如果互斥锁不可用,则返回
unlock unlocks the mutex
通常不直接访问std :: mutex:std :: unique_lock,std :: lock_guard或std :: scoped_lock(自C ++ 17起)以更加异常安全的方式管理锁定。
例
本示例说明了如何使用互斥锁来保护两个线程之间共享的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;
}