std::mutex
- cppreference
std::mutex
- cppreference
Defined in header <mutex>
- 定义于头文件 <mutex>
mutex:n. 互斥,互斥元,互斥体,互斥量
synchronization [ˌsɪŋkrənaɪˈzeɪʃn]:n. 同步,同时性
primitive [ˈprɪmətɪv]:adj. 原始的,远古的,简单的,粗糙的 n. 原始人
simultaneously [ˌsɪmlˈteɪniəsli]:adv. 同时地
exclusive [ɪkˈskluːsɪv]:adj. 独有的,排外的,专一的 n. 独家新闻,独家经营的项目,排外者
semantics [sɪˈmæntɪks]:n. 语义学,语义论
recursive [rɪˈkɜːsɪv]:adj. 递归的,循环的
1. std::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
类是能用于保护共享数据免受从多个线程同时访问的同步原语。
mutex
offers exclusive, non-recursive ownership semantics:
mutex
提供排他性非递归所有权语义:
-
A calling thread owns a
mutex
from the time that it successfully calls eitherlock
ortry_lock
until it callsunlock
.
调用线程从它成功调用lock
或try_lock
开始,到它调用unlock
为止占有mutex
。 -
When a thread owns a
mutex
, all other threads will block (for calls tolock
) or receive afalse
return value (fortry_lock
) if they attempt to claim ownership of themutex
.
线程占有mutex
时,所有其他线程若试图要求mutex
的所有权,则将阻塞 (对于lock
的调用) 或收到false
返回值 (对于try_lock
). -
A calling thread must not own the
mutex
prior to callinglock
ortry_lock
.
调用线程在调用lock
或try_lock
前必须不占有mutex
。
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
.
若 mutex
在仍为任何线程所占有时即被销毁,或在占有 mutex
时线程终止,则行为未定义。mutex
类满足互斥体 (Mutex
) 和标准布局类型 (StandardLayoutType
) 的全部要求。
std::mutex
is neither copyable nor movable.
std::mutex
既不可复制亦不可移动。
2. Member types - 成员类型
native_handle_type
(optional - 可选) - implementation-defined (实现定义)
3. Member functions - 成员函数
member function (成员函数) | public member function (公开成员函数) |
---|---|
constructor (构造函数) |
constructs the mutex (构造互斥) |
destructor (析构函数) |
destroys the mutex (销毁互斥) |
operator=[deleted] |
not copy-assignable (不可复制赋值) |
4. Locking - 锁定
lock
- locks the mutex, blocks if the mutex is not available (public member function) - 锁定互斥,若互斥不可用则阻塞 (公开成员函数)
try_lock
- tries to lock the mutex, returns if the mutex is not available (public member function) - 尝试锁定互斥,若互斥不可用则返回 (公开成员函数)
unlock
- unlocks the mutex (public member function) - 解锁互斥 (公开成员函数)
5. Native handle - 原生句柄
native_handle
- returns the underlying implementation-defined native handle object (public member function) - 返回底层实现定义的原生句柄 (公开成员函数)
std::mutex
is usually not accessed directly: std::unique_lock
, std::lock_guard
, or std::scoped_lock
(since C++17) manage locking in a more exception-safe manner.
通常不直接使用 std::mutex
:std::unique_lock
, std::lock_guard
, or std::scoped_lock
(C++17 起) 以更加异常安全的方式管理锁定。
6. Example - 示例
This example shows how a mutex
can be used to protect an std::map
shared between two threads.
此示例展示 mutex
能如何用于在保护共享于二个线程间的 std::map
。
//============================================================================
// Name : std::mutex
// Author : Yongqiang Cheng
// Version : Version 1.0.0
// Copyright : Copyright (c) 2019 Yongqiang Cheng
// Description : Hello World in C++, Ansi-style
//============================================================================
#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 EXIT_SUCCESS;
}
http://bar => fake content
http://foo => fake content