std::mutex

定义于头文件 <mutex>
class mutex;
(C++11 起)

mutex 类是能用于保护共享数据免受从多个线程同时访问的同步原语。

mutex 提供排他性非递归所有权语义:

mutex 在仍为任何线程所占有时即被销毁,或在占有 mutex 时线程终止,则行为未定义。 mutex 类满足互斥 (Mutex) 和标准布局类型 (StandardLayoutType) 的全部要求。

std::mutex 既不可复制亦不可移动。

目录

成员类型

成员类型 定义
native_handle_type(可选) 实现定义

成员函数

构造互斥
(公开成员函数)
销毁互斥
(公开成员函数)
operator=
[删除]
不可复制赋值
(公开成员函数)
锁定
锁定互斥,若互斥不可用则阻塞
(公开成员函数)
尝试锁定互斥,若互斥不可用则返回
(公开成员函数)
解锁互斥
(公开成员函数)
原生句柄
返回底层实现定义的线程句柄
(公开成员函数)

注意

通常不直接使用 std::mutexstd::unique_lockstd::lock_guard std::scoped_lock (C++17 起)以更加异常安全的方式管理锁定。

示例

此示例展示 mutex 能如何用于在保护共享于二个线程间的 std::map

#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)
{
    // 模拟长页面读取
    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();
 
    // 现在不用锁访问 g_pages 是安全的,因为线程已结合
    for (const auto &pair : g_pages) {
        std::cout << pair.first << " => " << pair.second << '\n';
    }
}

输出:

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

版本历史

  • (当前 | 先前 2017年8月25日 (五) 04:39Fruderica讨论 | 贡献. . (3,011字节) (-1,019). . (撤销)
  • 当前 | 先前 2013年7月9日 (二) 02:04P12bot讨论 | 贡献 . . (4,030字节) (+6). . (Allow search engines to index popular pages.) (撤销)
  • 当前 | 先前 2013年7月2日 (二) 11:32P12bot讨论 | 贡献 . . (4,024字节) (-118). . (Use {{lc}}. Update links. Various fixes.) (撤销)
  • 当前 | 先前 2012年11月2日 (五) 19:40P12bot讨论 | 贡献 . . (4,142字节) (+193). . (r2.7.3) (机器人添加:de, en, es, fr, it, ja, pt, ru) (撤销)
  • 当前 | 先前 2012年10月26日 (五) 03:08P12讨论 | 贡献 . . (3,949字节) (0). . (1个修订: Translate from the English version) (撤销)
  • 当前 | 先前) 2012年10月25日 (四) 12:00TranslationBot讨论 | 贡献. . (3,949字节) (+3,949). . (Translated from the English version using Google Translate)