这几篇都是拜读大神后,记录下来的笔记,链接https://www.cnblogs.com/haippy/p/3284540.html

Mutex 又称互斥量,C++ 11中与 Mutex 相关的类(包括锁类型)和函数都声明在 < mutex > 头文件中,所以需要使用 std::mutex,就必须包含 < mutex > 头文件。

< mutex >头文件

Mutex系列类

  • std::mutex,最基本的 Mutex 类。
  • std::recursive_mutex,递归 Mutex 类。
  • std::time_mutex,定时 Mutex 类。
  • std::recursive_timed_mutex,定时递归 Mutex 类。

Lock类

  • std::lock_guard,与 Mutex RAII 相关,方便线程对互斥量上锁。
  • std::unique_lock,与 Mutex RAII 相关,方便线程对互斥量上锁,但提供了更好的上锁和解锁控制。

其他类型

  • std::once_flag
  • std::adopt_lock_t
  • std::defer_lock_t
  • std::try_to_lock_t

函数

  • std::try_lock,尝试同时对多个互斥量上锁。
  • std::lock,可以同时对多个互斥量上锁。
  • std::call_once,如果多个线程需要同时调用某个函数,call_once 可以保证多个线程对该函数只调用一次。

std::mutex

std::mutex 是C++11 中最基本的互斥量,std::mutex 对象提供了独占所有权的特性——即不支持递归地对 std::mutex 对象上锁,而 std::recursive_lock 则可以递归地对互斥量对象上锁。

  • 构造函数,std::mutex不允许拷贝构造,也不允许 move 拷贝,最初产生的 mutex 对象是处于 unlocked 状态的。
  • lock(),调用线程将锁住该互斥量。线程调用该函数会发生下面 3 种情况:(1). 如果该互斥量当前没有被锁住,则调用线程将该互斥量锁住,直到调用 unlock之前,该线程一直拥有该锁。(2). 如果当前互斥量被其他线程锁住,则当前的调用线程被阻塞住。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。
  • unlock(), 解锁,释放对互斥量的所有权。
  • try_lock(),尝试锁住互斥量,如果互斥量被其他线程占有,则当前线程也不会被阻塞。线程调用该函数也会出现下面 3 种情况,(1). 如果当前互斥量没有被其他线程占有,则该线程锁住互斥量,直到该线程调用 unlock 释放互斥量。(2). 如果当前互斥量被其他线程锁住,则当前调用线程返回 false,而并不会被阻塞掉。(3). 如果当前互斥量被当前调用线程锁住,则会产生死锁(deadlock)。

举个例子:

#include <iostream>         // std::cout
#include <thread>            // std::thread
#include <mutex>            // std::mutexvolatile int counter(0);     // non-atomic counter
std::mutex mtx;                // locks access to countervoid attempt_10k_increases() {for (int i=0; i<10000; ++i) {if (mtx.try_lock()) {            // only increase if currently not locked:++counter;mtx.unlock();}}
}int main () {std::thread threads[10];for (int i=0; i<10; ++i) {threads[i] = std::thread(attempt_10k_increases);}for (auto& th : threads) {th.join();}std::cout << counter << " successful increases of the counter.\n";return 0;
}

std::recursive_mutex

std::recursive_mutex 与 std::mutex 一样,也是一种可以被上锁的对象,但是和 std::mutex 不同的是,std::recursive_mutex 允许同一个线程对互斥量多次上锁(即递归上锁),来获得对互斥量对象的多层所有权,std::recursive_mutex 释放互斥量时需要调用与该锁层次深度相同次数的 unlock(),可理解为 lock() 次数和 unlock() 次数相同,除此之外,std::recursive_mutex 的特性和 std::mutex 大致相同。

std::time_mutex

std::time_mutex 比 std::mutex 多了两个成员函数,try_lock_for(),try_lock_until()。

  • try_lock_for 函数接受一个时间范围,表示在这一段时间范围之内线程如果没有获得锁则被阻塞住(与 std::mutex 的 try_lock() 不同,try_lock 如果被调用时没有获得锁则直接返回 false),如果在此期间其他线程释放了锁,则该线程可以获得对互斥量的锁,如果超时(即在指定时间内还是没有获得锁),则返回 false。

  • try_lock_until 函数则接受一个时间点作为参数,在指定时间点未到来之前线程如果没有获得锁则被阻塞住,如果在此期间其他线程释放了锁,则该线程可以获得对互斥量的锁,如果超时(即在指定时间内还是没有获得锁),则返回 false。

下面的小例子说明了 std::time_mutex 的用法:

#include <iostream>       // std::cout
#include <chrono>         // std::chrono::milliseconds
#include <thread>          // std::thread
#include <mutex>          // std::timed_mutexstd::timed_mutex mtx;void fireworks() {// waiting to get a lock: each thread prints "-" every 200ms:while (!mtx.try_lock_for(std::chrono::milliseconds(200))) {std::cout << "-";}// got a lock! - wait for 1s, then this thread prints "*"std::this_thread::sleep_for(std::chrono::milliseconds(1000));std::cout << "*\n";mtx.unlock();
}int main ()
{std::thread threads[10];// spawn 10 threads:for (int i=0; i<10; ++i) {threads[i] = std::thread(fireworks);}for (auto& th : threads) {th.join();}return 0;
}

std::recursive_timed_mutex

和 std:recursive_mutex 与 std::mutex 的关系一样,std::recursive_timed_mutex 的特性也可以从 std::timed_mutex 推导出来,可以自行查阅下资料。

std::lock_guard

与 Mutex RAII 相关,方便线程对互斥量上锁。

#include <iostream>        // std::cout
#include <thread>           // std::thread
#include <mutex>           // std::mutex, std::lock_guard
#include <stdexcept>     // std::logic_errorstd::mutex mtx;void print_even (int x) {if (x%2==0) std::cout << x << " is even\n";else throw (std::logic_error("not even"));
}void print_thread_id (int id) {try {// using a local lock_guard to lock mtx guarantees unlocking on destruction / exception:std::lock_guard<std::mutex> lck (mtx);print_even(id);}catch (std::logic_error&) {std::cout << "[exception caught]\n";}
}int main ()
{std::thread threads[10];// spawn 10 threads:for (int i=0; i<10; ++i)threads[i] = std::thread(print_thread_id,i+1);for (auto& th : threads) th.join();return 0;
}

std::unique_lock

与std::lock_guard类似。另外的文章中有详细说明。

#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::unique_lockstd::mutex mtx;           // mutex for critical sectionvoid print_block (int n, char c) {// critical section (exclusive access to std::cout signaled by lifetime of lck):std::unique_lock<std::mutex> lck (mtx);for (int i=0; i<n; ++i) {std::cout << c;}std::cout << '\n';
}int main ()
{std::thread th1 (print_block,50,'*');std::thread th2 (print_block,50,'$');th1.join();th2.join();return 0;
}

C++ 并发指南 std::mutex相关推荐

  1. C++11 并发指南------std::thread 详解

    参考: https://github.com/forhappy/Cplusplus-Concurrency-In-Practice/blob/master/zh/chapter3-Thread/Int ...

  2. C++ 并发指南 std::lock

    C++11 标准为我们提供了两种基本的锁类型,分别如下: std::lock_guard,与 Mutex RAII 相关,方便线程对互斥量上锁. std::unique_lock,与 Mutex RA ...

  3. C++11 并发指南三(std::mutex 详解)

    上一篇<C++11 并发指南二(std::thread 详解)>中主要讲到了 std::thread 的一些用法,并给出了两个小例子,本文将介绍 std::mutex 的用法. Mutex ...

  4. 【转】C++11 并发指南五(std::condition_variable 详解)

    http://www.cnblogs.com/haippy/p/3252041.html 前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三 ...

  5. C++11 并发指南五(std::condition_variable 详解)

    前面三讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread,std::mut ...

  6. C++11 并发指南四(future 详解一 std::promise 介绍)

    前面两讲<C++11 并发指南二(std::thread 详解)>,<C++11 并发指南三(std::mutex 详解)>分别介绍了 std::thread 和 std::m ...

  7. 【C/C++开发】C++11 并发指南二(std::thread 详解)

    上一篇博客<C++11 并发指南一(C++11 多线程初探)>中只是提到了 std::thread 的基本用法,并给出了一个最简单的例子,本文将稍微详细地介绍 std::thread 的用 ...

  8. C++11 并发指南六(atomic 类型详解三 std::atomic (续))

    C++11 并发指南六( <atomic> 类型详解二 std::atomic ) 介绍了基本的原子类型 std::atomic 的用法,本节我会给大家介绍C++11 标准库中的 std: ...

  9. C++11 并发指南六( atomic 类型详解二 std::atomic )

    C++11 并发指南六(atomic 类型详解一 atomic_flag 介绍)  一文介绍了 C++11 中最简单的原子类型 std::atomic_flag,但是 std::atomic_flag ...

最新文章

  1. 使用docker部署mysql 并持久化到宿主机本地
  2. iOS之UI--涂鸦画板实例
  3. TCP/IP详解--学习笔记(7)-广播和多播,IGMP协议
  4. python 学习笔记day03-python基础、python对象、数字、函数
  5. plsql 存储过程 批量提交_Oracle 存储过程批量插入数据
  6. LeetCode Algorithm 102. 二叉树的层序遍历
  7. iphone android传照片大小,iPhone与安卓跨平台如何传照片图文教程
  8. 数据分析系统DIY1/3:CentOS7+MariaDB安装纪实
  9. centos7 网卡配置vlan_centos 7 下多网卡绑定+ vlan 网卡配置
  10. Android APK签名原理
  11. 计算机系统文字图片以啥子存在,电脑如何识别图片中文字的字体|电脑通过图片识别字体的方法...
  12. android 版本lollipop,Android 5.0 Lollipop系统BUG盘点
  13. 系统与软件过程改进09年年会,CMMI vs 敏捷PK赛参赛感言
  14. 点击word页面自动弹出信息检索
  15. [C#]使用Process的StandardInput与StandardOutput写入读取控制台数据
  16. Apk 拆包替换文件
  17. Centos Stream 9安装docker-ce
  18. yeah邮箱功能测试
  19. IE-LAB网络实验室:思科ccie,sp ccie 思科ccnp CCIE与HCIE哪个更好找工作
  20. 搜狗微信下线了怎么获取公众号文章?手把手教你最新获取方式

热门文章

  1. 怎么更改计算机wmi配置,WMI 远程计算机配置
  2. ASR PRO与 ESP8266 CP2102进行串口通信
  3. 原来我对 MySQL 一无所知
  4. 初中使用计算机教学反思,初中信息技术教学反思(通用5篇)
  5. 英国《金融时报》:全力加码早期投资,红杉中国在下一盘怎样的棋?...
  6. 表的概念(Oracle)
  7. 车间设备能源管理系统作用有哪些?
  8. 【box-shadow盒子内边阴影外阴影】
  9. google支持本地ajax,360chrome,google chrome浏览器使用jquery.ajax加载本地html文件
  10. 程序猿如何找到自己心仪的对象?