C++11 并发指南五(stdcondition_variable 详解)

news2024/9/24 3:30:09

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

文章目录

  • C++11 并发指南五(std::condition_variable 详解)
      • std::condition_variable 类介绍
      • std::condition_variable_any 介绍
      • std::cv_status 枚举类型介绍
      • std::notify_all_at_thread_exit

前面三讲《 C++11 并发指南二(std::thread 详解)》,《 C++11 并发指南三(std::mutex 详解)》分别介绍了 std::thread,std::mutex,std::future 等相关内容,相信读者对 C++11 中的多线程编程有了一个最基本的认识,本文将介绍 C++11 标准中 <condition_variable> 头文件里面的类和相关函数。

<condition_variable > 头文件主要包含了与条件变量相关的类和函数。相关的类包括 std::condition_variable 和 std::condition_variable_any,还有枚举类型std::cv_status。另外还包括函数 std::notify_all_at_thread_exit(),下面分别介绍一下以上几种类型。

std::condition_variable 类介绍

std::condition_variable 是条件变量,更多有关条件变量的定义参考维基百科。Linux 下使用 Pthread 库中的 pthread_cond_*() 函数提供了与条件变量相关的功能, Windows 则参考 MSDN。

当 std::condition_variable 对象的某个 wait 函数被调用的时候,它使用 std::unique_lock(通过 std::mutex) 来锁住当前线程。当前线程会一直被阻塞,直到另外一个线程在相同的 std::condition_variable 对象上调用了 notification 函数来唤醒当前线程。

std::condition_variable 对象通常使用 std::unique_lockstd::mutex 来等待,如果需要使用另外的 lockable 类型,可以使用 std::condition_variable_any 类,本文后面会讲到 std::condition_variable_any 的用法。

首先我们来看一个简单的例子

[复制代码](javascript:void(0)😉

#include <iostream>                // std::cout
#include <thread>                // std::thread
#include <mutex>                // std::mutex, std::unique_lock
#include <condition_variable>    // std::condition_variable

std::mutex mtx; // 全局互斥锁.
std::condition_variable cv; // 全局条件变量.
bool ready = false; // 全局标志位.

void do_print_id(int id)
{
    std::unique_lock <std::mutex> lck(mtx);
    while (!ready) // 如果标志位不为 true, 则等待...
        cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,
    // 线程被唤醒, 继续往下执行打印线程编号id.
    std::cout << "thread " << id << '\n';
}

void go()
{
    std::unique_lock <std::mutex> lck(mtx);
    ready = true; // 设置全局标志位为 true.
    cv.notify_all(); // 唤醒所有线程.
}

int main()
{
    std::thread threads[10];
    // spawn 10 threads:
    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(do_print_id, i);

    std::cout << "10 threads ready to race...\n";
    go(); // go!

  for (auto & th:threads)
        th.join();

    return 0;
}

[复制代码](javascript:void(0)😉

执行结果如下:

[复制代码](javascript:void(0)😉

concurrency ) ./ConditionVariable-basic1 
10 threads ready to race...
thread 1
thread 0
thread 2
thread 3
thread 4
thread 5
thread 6
thread 7
thread 8
thread 9

[复制代码](javascript:void(0)😉

好了,对条件变量有了一个基本的了解之后,我们来看看 std::condition_variable 的各个成员函数。

std::condition_variable 构造函数

default (1)condition_variable();
copy [deleted] (2)condition_variable (const condition_variable&) = delete;

std::condition_variable 的拷贝构造函数被禁用,只提供了默认构造函数。

std::condition_variable::wait() 介绍

unconditional (1)void wait (unique_lock<mutex>& lck);
predicate (2)template <class Predicate> void wait (unique_lock<mutex>& lck, Predicate pred);

std::condition_variable 提供了两种 wait() 函数。当前线程调用 wait() 后将被阻塞(此时当前线程应该获得了锁(mutex),不妨设获得锁 lck),直到另外某个线程调用 notify_* 唤醒了当前线程。

在线程被阻塞时,该函数会自动调用 lck.unlock() 释放锁,使得其他被阻塞在锁竞争上的线程得以继续执行。另外,一旦当前线程获得通知(notified,通常是另外某个线程调用 notify_* 唤醒了当前线程),wait() 函数也是自动调用 lck.lock(),使得 lck 的状态和 wait 函数被调用时相同。

在第二种情况下(即设置了 Predicate),只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞。因此第二种情况类似以下代码:

while (!pred()) wait(lck);

请看下面例子(参考):

[复制代码](javascript:void(0)😉

#include <iostream>                // std::cout
#include <thread>                // std::thread, std::this_thread::yield
#include <mutex>                // std::mutex, std::unique_lock
#include <condition_variable>    // std::condition_variable

std::mutex mtx;
std::condition_variable cv;

int cargo = 0;
bool shipment_available()
{
    return cargo != 0;
}

// 消费者线程.
void consume(int n)
{
    for (int i = 0; i < n; ++i) {
        std::unique_lock <std::mutex> lck(mtx);
        cv.wait(lck, shipment_available);
        std::cout << cargo << '\n';
        cargo = 0;
    }
}

int main()
{
    std::thread consumer_thread(consume, 10); // 消费者线程.

    // 主线程为生产者线程, 生产 10 个物品.
    for (int i = 0; i < 10; ++i) {
        while (shipment_available())
            std::this_thread::yield();
        std::unique_lock <std::mutex> lck(mtx);
        cargo = i + 1;
        cv.notify_one();
    }

    consumer_thread.join();

    return 0;
}

[复制代码](javascript:void(0)😉

程序执行结果如下:

[复制代码](javascript:void(0)😉

concurrency ) ./ConditionVariable-wait 
1
2
3
4
5
6
7
8
9
10

[复制代码](javascript:void(0)😉

std::condition_variable::wait_for() 介绍

unconditional (1)template <class Rep, class Period> cv_status wait_for (unique_lock<mutex>& lck, const chrono::duration<Rep,Period>& rel_time);
predicate (2)template <class Rep, class Period, class Predicate> bool wait_for (unique_lock<mutex>& lck, const chrono::duration<Rep,Period>& rel_time, Predicate pred);

std::condition_variable::wait() 类似,不过 wait_for 可以指定一个时间段,在当前线程收到通知或者指定的时间 rel_time 超时之前,该线程都会处于阻塞状态。而一旦超时或者收到了其他线程的通知,wait_for 返回,剩下的处理步骤和 wait() 类似。

另外,wait_for 的重载版本(predicte(2))的最后一个参数 pred 表示 wait_for 的预测条件,只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞,因此相当于如下代码:

return wait_until (lck, chrono::steady_clock::now() + rel_time, std::move(pred));

请看下面的例子(参考),下面的例子中,主线程等待 th 线程输入一个值,然后将 th 线程从终端接收的值打印出来,在 th 线程接受到值之前,主线程一直等待,每个一秒超时一次,并打印一个 “.”:

[复制代码](javascript:void(0)😉

#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <chrono>             // std::chrono::seconds
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable, std::cv_status

std::condition_variable cv;

int value;

void do_read_value()
{
    std::cin >> value;
    cv.notify_one();
}

int main ()
{
    std::cout << "Please, enter an integer (I'll be printing dots): \n";
    std::thread th(do_read_value);

    std::mutex mtx;
    std::unique_lock<std::mutex> lck(mtx);
    while (cv.wait_for(lck,std::chrono::seconds(1)) == std::cv_status::timeout) {
        std::cout << '.';
        std::cout.flush();
    }

    std::cout << "You entered: " << value << '\n';

    th.join();
    return 0;
}

[复制代码](javascript:void(0)😉

**std::condition_variable::wait_until 介绍
**

unconditional (1)template <class Clock, class Duration> cv_status wait_until (unique_lock<mutex>& lck, const chrono::time_point<Clock,Duration>& abs_time);
predicate (2)template <class Clock, class Duration, class Predicate> bool wait_until (unique_lock<mutex>& lck, const chrono::time_point<Clock,Duration>& abs_time, Predicate pred);

std::condition_variable::wait_for 类似,但是 wait_until 可以指定一个时间点,在当前线程收到通知或者指定的时间点 abs_time 超时之前,该线程都会处于阻塞状态。而一旦超时或者收到了其他线程的通知,wait_until 返回,剩下的处理步骤和 wait_until() 类似。

另外,wait_until 的重载版本(predicte(2))的最后一个参数 pred 表示 wait_until 的预测条件,只有当 pred 条件为 false 时调用 wait() 才会阻塞当前线程,并且在收到其他线程的通知后只有当 pred 为 true 时才会被解除阻塞,因此相当于如下代码:

while (!pred())
  if ( wait_until(lck,abs_time) == cv_status::timeout)
    return pred();
return true;

std::condition_variable::notify_one() 介绍

唤醒某个等待(wait)线程。如果当前没有等待线程,则该函数什么也不做,如果同时存在多个等待线程,则唤醒某个线程是不确定的(unspecified)。

请看下例(参考):

[复制代码](javascript:void(0)😉

#include <iostream>                // std::cout
#include <thread>                // std::thread
#include <mutex>                // std::mutex, std::unique_lock
#include <condition_variable>    // std::condition_variable

std::mutex mtx;
std::condition_variable cv;

int cargo = 0; // shared value by producers and consumers

void consumer()
{
    std::unique_lock < std::mutex > lck(mtx);
    while (cargo == 0)
        cv.wait(lck);
    std::cout << cargo << '\n';
    cargo = 0;
}

void producer(int id)
{
    std::unique_lock < std::mutex > lck(mtx);
    cargo = id;
    cv.notify_one();
}

int main()
{
    std::thread consumers[10], producers[10];

    // spawn 10 consumers and 10 producers:
    for (int i = 0; i < 10; ++i) {
        consumers[i] = std::thread(consumer);
        producers[i] = std::thread(producer, i + 1);
    }

    // join them back:
    for (int i = 0; i < 10; ++i) {
        producers[i].join();
        consumers[i].join();
    }

    return 0;
}

[复制代码](javascript:void(0)😉

std::condition_variable::notify_all() 介绍

唤醒所有的等待(wait)线程。如果当前没有等待线程,则该函数什么也不做。请看下面的例子:

[复制代码](javascript:void(0)😉

#include <iostream>                // std::cout
#include <thread>                // std::thread
#include <mutex>                // std::mutex, std::unique_lock
#include <condition_variable>    // std::condition_variable

std::mutex mtx; // 全局互斥锁.
std::condition_variable cv; // 全局条件变量.
bool ready = false; // 全局标志位.

void do_print_id(int id)
{
    std::unique_lock <std::mutex> lck(mtx);
    while (!ready) // 如果标志位不为 true, 则等待...
        cv.wait(lck); // 当前线程被阻塞, 当全局标志位变为 true 之后,
    // 线程被唤醒, 继续往下执行打印线程编号id.
    std::cout << "thread " << id << '\n';
}

void go()
{
    std::unique_lock <std::mutex> lck(mtx);
    ready = true; // 设置全局标志位为 true.
    cv.notify_all(); // 唤醒所有线程.
}

int main()
{
    std::thread threads[10];
    // spawn 10 threads:
    for (int i = 0; i < 10; ++i)
        threads[i] = std::thread(do_print_id, i);

    std::cout << "10 threads ready to race...\n";
    go(); // go!

  for (auto & th:threads)
        th.join();

    return 0;
}

[复制代码](javascript:void(0)😉

std::condition_variable_any 介绍

与 std::condition_variable 类似,只不过 std::condition_variable_any 的 wait 函数可以接受任何 lockable 参数,而 std::condition_variable 只能接受 std::unique_lockstd::mutex 类型的参数,除此以外,和 std::condition_variable 几乎完全一样。

std::cv_status 枚举类型介绍

cv_status::no_timeoutwait_for 或者 wait_until 没有超时,即在规定的时间段内线程收到了通知。
cv_status::timeoutwait_for 或者 wait_until 超时。

std::notify_all_at_thread_exit

函数原型为:

void notify_all_at_thread_exit (condition_variable& cond, unique_lock<mutex> lck);

当调用该函数的线程退出时,所有在 cond 条件变量上等待的线程都会收到通知。请看下例(参考):

[复制代码](javascript:void(0)😉

#include <iostream>           // std::cout
#include <thread>             // std::thread
#include <mutex>              // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id (int id) {
  std::unique_lock<std::mutex> lck(mtx);
  while (!ready) cv.wait(lck);
  // ...
  std::cout << "thread " << id << '\n';
}

void go() {
  std::unique_lock<std::mutex> lck(mtx);
  std::notify_all_at_thread_exit(cv,std::move(lck));
  ready = true;
}

int main ()
{
  std::thread threads[10];
  // spawn 10 threads:
  for (int i=0; i<10; ++i)
    threads[i] = std::thread(print_id,i);
  std::cout << "10 threads ready to race...\n";

  std::thread(go).detach();   // go!

  for (auto& th : threads) th.join();

  return 0;
}

[复制代码](javascript:void(0)😉

好了,到此为止,<condition_variable> 头文件中的两个条件变量类(std::condition_variable 和 std::condition_variable_any)、枚举类型(std::cv_status)、以及辅助函数(std::notify_all_at_thread_exit())都已经介绍完了。从下一章开始我会逐步开始介绍 头文件中的内容,后续的文章还会介绍 C++11 的内存模型,涉及内容稍微底层一些,希望大家能够保持兴趣,学完 C++11 并发编程,如果你发现本文中的错误,也请给我反馈 😉。

// go!

for (auto& th : threads) th.join();

return 0;
}


[[外链图片转存中...(img-gtqCwzRS-1674832542941)]](javascript:void(0);)

 

好了,到此为止,<condition_variable> 头文件中的两个条件变量类(std::condition_variable 和 std::condition_variable_any)、枚举类型(std::cv_status)、以及辅助函数(std::notify_all_at_thread_exit())都已经介绍完了。从下一章开始我会逐步开始介绍 <atomic> 头文件中的内容,后续的文章还会介绍 C++11 的内存模型,涉及内容稍微底层一些,希望大家能够保持兴趣,学完 C++11 并发编程,如果你发现本文中的错误,也请给我反馈 ;-)。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/181458.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

二叉树简单解析(1)

&#x1f340;本人简介&#xff1a; 吉师大一最爱逃课的混子、 华为云享专家、阿里云专家博主、腾讯云自媒体分享计划博主、 华为MindSpore优秀开发者、迷雾安全团队核心成员&#xff0c;CSDN2022年运维与安全领域第15名 &#x1f341;本人制作小程序以及资源分享地址&#x…

英语学习打卡day7

2023.1.27 1.ironically adv.具有讽刺意味的是;反讽地&#xff0c;讽刺地 Ironically, his cold got better on the last day of his holiday. 2.bequeath vt.遗赠;把…遗赠给;把… .传给 (比give更正式) bequeath sb sth bequeath sth to sb Don’t bequeath the problem …

JDK17 || JDK 8 完美 卸载 教程 (Windows版)

文章目录一、卸载jdk程序1 . 找到控制面板2. 卸载程序3. 找到JDK 相关的程序4. 右键 选择卸载程序5. 下一步 选择 是6.下一步 选择 是二、安装 新版 JDK三、如果不想再使用jdk环境结语一、卸载jdk程序 1 . 找到控制面板 2. 卸载程序 3. 找到JDK 相关的程序 4. 右键 选择卸载程…

IDEA界面和控制台的滚动条颜色不明显?赶快换一个吧!

前言 不知道大家是否和我一样有这么一个烦恼&#xff1a; IDEA自带的滚动条颜色很暗&#xff0c;配上一些主题颜色搭配很难发现。 所以今天就想着怎么可以修改滚动条颜色&#xff0c;首先去网上搜了搜都是什么鼠标滚轮加shift滚动&#xff0c;一点也不实用 偶然看到了个不错的…

【青训营】Go的BenchMark的使用

本文内容总结于 字节跳动青年训练营 第五届后端组 Go自带了一些性能测试工具&#xff0c;其中BenchMark是较为重要的一个。 我们以计算斐波那契数列的示例来展示BenchMark的使用 package Benchmarkimport "testing"func Fib(n int) int {if n < 2 {return n}ret…

OpenCV-PyQT项目实战(1)安装与环境配置

本系列从零开始实战解说基于 PyQt5 的 OpenCV 项目开发。 欢迎关注『OpenCV-PyQT项目实战 Youcans』系列&#xff0c;持续更新中 OpenCV-PyQT项目实战&#xff08;1&#xff09;安装与环境配置 OpenCV-PyQT项目实战&#xff08;2&#xff09;OpenCV导入图像 文章目录1. PyQt5 …

初识图像分类——K近邻法(cs231n assignment)

作者&#xff1a;非妃是公主 专栏&#xff1a;《计算机视觉》 个性签&#xff1a;顺境不惰&#xff0c;逆境不馁&#xff0c;以心制境&#xff0c;万事可成。——曾国藩 专栏系列文章 Cannot find reference ‘imread‘ in ‘init.py‘ error: (-209:Sizes of input arguments…

ppt神器islide 第1节 初步接触强大的工具-资源篇

ppt神器islide 第1节 初步接触强大的工具1 PPT大神的课程总结1.1 骨架篇1.2 色彩篇1.3 对齐篇1.4 对比篇1.5 修饰篇1.6 字体篇1.7 素材篇1.8 线条篇1.8.1 可以随意画线条&#xff0c;填充空白1.8.2 在字体上画线条&#xff0c;做成艺术字1.8.3 做对称线条&#xff0c;比如递进三…

[Vulnhub] DC-3

下载链接&#xff1a;DC-3 DC-3需要 把IDE里面的改成IDE 0:0 不然无法打开 知识点&#xff1a; Joomla cms 3.7.0 sql注入漏洞cmseek工具探测cms指纹john解密proc_popen反弹shellpython -m http.server开启http服务 & wget远程下载ubuntu16.0.4 Linux 4.4.0-21 系统漏…

使用OpenAI的Whisper 模型进行语音识别

语音识别是人工智能中的一个领域&#xff0c;它允许计算机理解人类语音并将其转换为文本。该技术用于 Alexa 和各种聊天机器人应用程序等设备。而我们最常见的就是语音转录&#xff0c;语音转录可以语音转换为文字记录或字幕。 wav2vec2、Conformer 和 Hubert 等最先进模型的最…

无穷小的比较——“高等数学”

各位CSDN的uu们你们好呀&#xff0c;今天小雅兰的内容是无穷小的比较&#xff0c;下面&#xff0c;就让我们一起进入高等数学的世界吧 回顾 定义 性质 定理 定理1&#xff1a; 定理2&#xff1a;等价无穷小替换定理 常用的等价无穷小 例题 小结 回顾 两个无穷小的商当然不一定还…

Android深入系统完全讲解(38)

9.6 配置 native 方法 9.6.1 CMakeLists.txt 文件中内容&#xff0c;配置生成一个 so 库add_library( # Sets the name of the library. native-lib # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). src/main/cpp/native…

一刷代码随想录——数组

概念数组是存放在连续内存空间上的相同类型数据的集合连续&#xff1a;增删需移动后续元素&#xff0c;删除的本质是覆盖类型&#xff1a;相同用数组&#xff0c;不同用结构数组下标从0开始C中二维数组连续分布vector的底层实现是array&#xff0c;严格来讲vector是容器&#x…

C++11 并发指南四( 详解三 stdfuture stdshared_future)

C11 并发指南四( 详解三 std::future & std::shared_future) 文章目录C11 并发指南四( 详解三 std::future & std::shared_future)std::future 介绍std::future 成员函数std::shared_future 介绍std::future_error 介绍其他与 std::future 相关的函数介绍其他与 std::f…

SWIFT Framework .NET 2023.1 Crack

SWIFT 组件 SWIFT Components 多年来一直致力于银行机构软件、在线交易软件、CRM 和零售和商业解决方案中的计费应用程序&#xff0c;以及医药和高度关键任务的 24/7 运营应用程序。作为定制银行解决方案的开发商&#xff0c;SWIFT Components 拥有所有银行产品和部门的专业知识…

【python从零入门 | 03】基本数据类型之“除法“

🍁博主简介: 🏅云计算领域优质创作者 🏅2022年CSDN新星计划python赛道第一名 🏅2022年CSDN原力计划优质作者 🏅阿里云ACE认证高级工程师 🏅阿里云开发者社区专家博主 💊交流社区:CSDN云计算交流社区欢迎您的加入! 目

设置/恢复系统隐藏文件 - Windows系统

设置/恢复系统隐藏文件 - Windows系统前言普通隐藏文件显示文件设置/取消隐藏系统隐藏文件显示文件设置/取消隐藏前言 本文介绍Windows系统如何设置/恢复隐藏文件&#xff0c;隐藏文件包含普通隐藏文件和系统隐藏文件&#xff0c;系统隐藏文件一般是受保护的系统文件&#xff…

Android 蓝牙开发——Avrcp协议(十二)

SDK路径&#xff1a;frameworks/base/core/java/android/bluetooth/ 服务路径&#xff1a;packages/apps/Bluetooth/src/com/android/bluetooth/ 在使用协议类的时候无法找到该类&#xff0c;由于安卓源码中关于蓝牙协议的 Client 部分或相关接口都被 hide 给隐藏掉了&#xf…

【通信原理(含matlab程序)】实验一 双边带模拟调制和解调

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; 本人持续分享更多关于电子通信专业内容以及嵌入式和单片机的知识&#xff0c;如果大家喜欢&#xff0c;别忘点个赞加个关注哦&#xff0c;让我们一起共同进步~ &#x…

AcWing - 寒假每日一题2023(DAY 11——DAY 15)

文章目录一、AcWing 4656. 技能升级&#xff08;困难&#xff09;1. 实现思路2. 实现代码二、AcWing 4454. 未初始化警告&#xff08;简单&#xff09;1. 实现思路2. 实现代码三、AcWing 4509. 归一化处理&#xff08;简单&#xff09;1. 实现思路2. 实现代码四、AcWing 4699. …