C++并发之条件变量(std::condition_variable)

2024-06-15 19:04

本文主要是介绍C++并发之条件变量(std::condition_variable),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

目录

  • 1 概述
  • 2 使用实例
  • 3 接口使用
    • 3.1 wait
    • 3.2 wait_for
    • 3.3 wait_until
    • 3.4 notify_one
    • 3.5 notiry_all
    • 3.5 notify_all_at_thread_exit

1 概述

  条件变量是一个能够阻塞调用线程直到被通知恢复的对象。
  当调用其中一个等待函数时,它使用unique_lock(通过互斥锁)来锁定线程。线程保持阻塞状态,直到被另一个调用同一condition_variable对象上的通知函数的线程唤醒。
  条件变量类型的对象总是使用unique_lock来等待.
其类图如下:
类图

2 使用实例

struct Function4NotiryAll
{bool is_ready = false;std::mutex mutex;std::condition_variable cv;int counter = 0;void print_id(int id){std::unique_lock<std::mutex> lock(mutex);while(!is_ready)cv.wait(lock);std::cerr << "id:" << id << std::endl;counter++;}void go(){std::unique_lock<std::mutex> lock(mutex);is_ready = true;cv.notify_all();}
};void ConditionVariableSuite::notiry_all()
{std::thread threads[10];Function4NotiryAll function;for(int i = 0; i < 10; ++i)threads[i] = std::thread(&Function4NotiryAll::print_id, std::ref(function), i);function.go();for(auto & thread : threads)thread.join();TEST_ASSERT_EQUALS(true, function.counter == 10)
}

3 接口使用

3.1 wait

struct Function4Wait
{volatile int cargo = 0;int counter = 0;std::mutex mutex;std::condition_variable cv;inline bool have_cargo() { return cargo != 0; }inline void consume_cargo() { cargo = 0; }void consume(int n){for(int i = 0; i < n; i++){std::unique_lock<std::mutex> lock(mutex);while(!have_cargo())cv.wait(lock);std::cerr << "cargo: " << cargo << std::endl;counter++;consume_cargo();}}void consume_with_predicate(int n){for(int i = 0; i < n; i++){std::unique_lock<std::mutex> lock(mutex);cv.wait(lock, std::bind(&Function4Wait::have_cargo, this));std::cerr << "cargo: " << cargo << std::endl;counter++;consume_cargo();}}inline void product(int n){std::unique_lock<std::mutex> lock(mutex);cargo = n;cv.notify_one();}
};void ConditionVariableSuite::wait()
{Function4Wait function;  std::thread thread[2];int n = 10;thread[0] = std::thread(&Function4Wait::consume, std::ref(function), 10);for(int i = 0; i < n; i++){while(function.have_cargo())std::this_thread::yield();function.product(i + 1);}thread[0].join();TEST_ASSERT_EQUALS(true, function.counter == 10)function.counter = 0;thread[1] = std::thread(&Function4Wait::consume_with_predicate, std::ref(function), 10);for(int i = 0; i < n; i++){while(function.have_cargo())std::this_thread::yield();function.product(i + 1);}thread[1].join();TEST_ASSERT_EQUALS(true, function.counter == 10)
}

3.2 wait_for

struct Function4WaitFor
{volatile int cargo = 0;int counter = 0;std::mutex mutex;std::condition_variable cv;inline bool have_cargo() { return cargo != 0; }inline void consume_cargo() { cargo = 0; }void consume(int n){for(int i = 0; i < n; i++){std::unique_lock<std::mutex> lock(mutex);while(!have_cargo() && cv.wait_for(lock, std::chrono::seconds(1)) == std::cv_status::timeout);std::cerr << "cargo: " << cargo << std::endl;counter++;consume_cargo();}}void consume_with_predicate(int n){for(int i = 0; i < n; i++){std::unique_lock<std::mutex> lock(mutex);while(!cv.wait_for(lock, std::chrono::seconds(1), std::bind(&Function4WaitFor::have_cargo, this)));std::cerr << "cargo: " << cargo << std::endl;counter++;consume_cargo();}}inline void product(int n){std::unique_lock<std::mutex> lock(mutex);cargo = n;cv.notify_one();}
};void ConditionVariableSuite::wait_for()
{Function4WaitFor function;  std::thread thread[2];int n = 10;thread[0] = std::thread(&Function4WaitFor::consume, std::ref(function), 10);for(int i = 0; i < n; i++){while(function.have_cargo())std::this_thread::yield();function.product(i + 1);}thread[0].join();TEST_ASSERT_EQUALS(true, function.counter == 10)function.counter = 0;thread[1] = std::thread(&Function4WaitFor::consume_with_predicate, std::ref(function), 10);for(int i = 0; i < n; i++){while(function.have_cargo())std::this_thread::yield();function.product(i + 1);}thread[1].join();TEST_ASSERT_EQUALS(true, function.counter == 10)
}

3.3 wait_until

struct Function4WaitUntil
{volatile int cargo = 0;int counter = 0;std::mutex mutex;std::condition_variable cv;inline bool have_cargo() { return cargo != 0; }inline void consume_cargo() { cargo = 0; }void consume(int n){for(int i = 0; i < n; i++){std::unique_lock<std::mutex> lock(mutex);std::chrono::time_point<std::chrono::system_clock> timePoint = std::chrono::system_clock::now() + std::chrono::seconds(1);while(!have_cargo() && cv.wait_until(lock, timePoint) == std::cv_status::timeout);std::cerr << "cargo: " << cargo << std::endl;counter++;consume_cargo();}}void consume_with_predicate(int n){for(int i = 0; i < n; i++){std::unique_lock<std::mutex> lock(mutex);std::chrono::time_point<std::chrono::system_clock> timePoint = std::chrono::system_clock::now() + std::chrono::seconds(1);while(!cv.wait_until(lock, timePoint, std::bind(&Function4WaitUntil::have_cargo, this)));std::cerr << "cargo: " << cargo << std::endl;counter++;consume_cargo();}}inline void product(int n){std::unique_lock<std::mutex> lock(mutex);cargo = n;cv.notify_one();}
};void ConditionVariableSuite::wait_until()
{Function4WaitUntil function;  std::thread thread[2];int n = 10;thread[0] = std::thread(&Function4WaitUntil::consume, std::ref(function), 10);for(int i = 0; i < n; i++){while(function.have_cargo())std::this_thread::yield();function.product(i + 1);}thread[0].join();TEST_ASSERT_EQUALS(true, function.counter == 10)function.counter = 0;thread[1] = std::thread(&Function4WaitUntil::consume_with_predicate, std::ref(function), 10);for(int i = 0; i < n; i++){while(function.have_cargo())std::this_thread::yield();function.product(i + 1);}thread[1].join();TEST_ASSERT_EQUALS(true, function.counter == 10)
}

3.4 notify_one

struct Function4NotityOne
{int cargo = 0;int counter = 0;std::mutex mutex;std::condition_variable produce;std::condition_variable consume;void consumer(){std::unique_lock<std::mutex> lock(mutex);while(cargo == 0)consume.wait(lock);std::cerr << "cargo: " << cargo << std::endl;cargo = 0;counter++;produce.notify_one();}void producer(int id){std::unique_lock<std::mutex> lock(mutex);while(cargo != 0)produce.wait(lock);cargo = id;consume.notify_one();}
};
void ConditionVariableSuite::notify_one()
{std::thread consumers[10];std::thread producers[10];Function4NotityOne function;for(int i = 0; i < 10; ++i){consumers[i] = std::thread(&Function4NotityOne::consumer, std::ref(function));producers[i] = std::thread(&Function4NotityOne::producer, std::ref(function), i + 1);}for(int i = 0; i < 10; ++i){consumers[i].join();producers[i].join();}TEST_ASSERT_EQUALS(true, function.counter == 10)
}

3.5 notiry_all

struct Function4NotiryAll
{bool is_ready = false;std::mutex mutex;std::condition_variable cv;int counter = 0;void print_id(int id){std::unique_lock<std::mutex> lock(mutex);while(!is_ready)cv.wait(lock);std::cerr << "id:" << id << std::endl;counter++;}void go(){std::unique_lock<std::mutex> lock(mutex);is_ready = true;cv.notify_all();}void allgo(){std::unique_lock<std::mutex> lock(mutex);is_ready = true;std::notify_all_at_thread_exit(cv, std::move(lock));}
};void ConditionVariableSuite::notiry_all()
{std::thread threads[10];Function4NotiryAll function;for(int i = 0; i < 10; ++i)threads[i] = std::thread(&Function4NotiryAll::print_id, std::ref(function), i);function.go();for(auto & thread : threads)thread.join();TEST_ASSERT_EQUALS(true, function.counter == 10)
}

3.5 notify_all_at_thread_exit

void ConditionVariableSuite::notify_all_at_thread_exit()
{std::thread threads[10];Function4NotiryAll function;for(int i = 0; i < 10; ++i)threads[i] = std::thread(&Function4NotiryAll::print_id, std::ref(function), i);std::thread(&Function4NotiryAll::allgo, std::ref(function)).detach();for(auto & thread : threads)thread.join();TEST_ASSERT_EQUALS(true, function.counter == 10)   
}

说明:

  • notify_all_at_thread_exit 只能在线程中调用,在进程中调用将不起作用。

这篇关于C++并发之条件变量(std::condition_variable)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1064310

相关文章

关于C++中的虚拟继承的一些总结(虚拟继承,覆盖,派生,隐藏)

1.为什么要引入虚拟继承 虚拟继承是多重继承中特有的概念。虚拟基类是为解决多重继承而出现的。如:类D继承自类B1、B2,而类B1、B2都继承自类A,因此在类D中两次出现类A中的变量和函数。为了节省内存空间,可以将B1、B2对A的继承定义为虚拟继承,而A就成了虚拟基类。实现的代码如下: class A class B1:public virtual A; class B2:pu

C++对象布局及多态实现探索之内存布局(整理的很多链接)

本文通过观察对象的内存布局,跟踪函数调用的汇编代码。分析了C++对象内存的布局情况,虚函数的执行方式,以及虚继承,等等 文章链接:http://dev.yesky.com/254/2191254.shtml      论C/C++函数间动态内存的传递 (2005-07-30)   当你涉及到C/C++的核心编程的时候,你会无止境地与内存管理打交道。 文章链接:http://dev.yesky

C++的模板(八):子系统

平常所见的大部分模板代码,模板所传的参数类型,到了模板里面,或实例化为对象,或嵌入模板内部结构中,或在模板内又派生了子类。不管怎样,最终他们在模板内,直接或间接,都实例化成对象了。 但这不是唯一的用法。试想一下。如果在模板内限制调用参数类型的构造函数会发生什么?参数类的对象在模板内无法构造。他们只能从模板的成员函数传入。模板不保存这些对象或者只保存他们的指针。因为构造函数被分离,这些指针在模板外

C# 中变量未赋值能用吗,各种类型的初始值是什么

对于一个局部变量,如果未赋值,是不能使用的 对于属性,未赋值,也能使用有系统默认值,默认值如下: 对于 int 类型,默认值是 0;对于 int? 类型,默认值是 null;对于 bool 类型,默认值是 false;对于 bool? 类型,默认值是 null;对于 string 类型,默认值是 null;对于 string? 类型,哈哈,没有这种写法,会出错;对于 DateTime 类型,默

C++工程编译链接错误汇总VisualStudio

目录 一些小的知识点 make工具 可以使用windows下的事件查看器崩溃的地方 dumpbin工具查看dll是32位还是64位的 _MSC_VER .cc 和.cpp 【VC++目录中的包含目录】 vs 【C/C++常规中的附加包含目录】——头文件所在目录如何怎么添加,添加了以后搜索头文件就会到这些个路径下搜索了 include<> 和 include"" WinMain 和

Javascript高级程序设计(第四版)--学习记录之变量、内存

原始值与引用值 原始值:简单的数据即基础数据类型,按值访问。 引用值:由多个值构成的对象即复杂数据类型,按引用访问。 动态属性 对于引用值而言,可以随时添加、修改和删除其属性和方法。 let person = new Object();person.name = 'Jason';person.age = 42;console.log(person.name,person.age);//'J

C/C++的编译和链接过程

目录 从源文件生成可执行文件(书中第2章) 1.Preprocessing预处理——预处理器cpp 2.Compilation编译——编译器cll ps:vs中优化选项设置 3.Assembly汇编——汇编器as ps:vs中汇编输出文件设置 4.Linking链接——链接器ld 符号 模块,库 链接过程——链接器 链接过程 1.简单链接的例子 2.链接过程 3.地址和

C++必修:模版的入门到实践

✨✨ 欢迎大家来到贝蒂大讲堂✨✨ 🎈🎈养成好习惯,先赞后看哦~🎈🎈 所属专栏:C++学习 贝蒂的主页:Betty’s blog 1. 泛型编程 首先让我们来思考一个问题,如何实现一个交换函数? void swap(int& x, int& y){int tmp = x;x = y;y = tmp;} 相信大家很快就能写出上面这段代码,但是如果要求这个交换函数支持字符型

C++入门01

1、.h和.cpp 源文件 (.cpp)源文件是C++程序的实际实现代码文件,其中包含了具体的函数和类的定义、实现以及其他相关的代码。主要特点如下:实现代码: 源文件中包含了函数、类的具体实现代码,用于实现程序的功能。编译单元: 源文件通常是一个编译单元,即单独编译的基本单位。每个源文件都会经过编译器的处理,生成对应的目标文件。包含头文件: 源文件可以通过#include指令引入头文件,以使

SQL Server中,添加数据库到AlwaysOn高可用性组条件

1、将数据添加到AlwaysOn高可用性组,需要满足以下条件: 2、更多具体AlwaysOn设置,参考:https://msdn.microsoft.com/zh-cn/library/windows/apps/ff878487(v=sql.120).aspx 注:上述资源来自MSDN。