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

相关文章

SpringIntegration消息路由之Router的条件路由与过滤功能

《SpringIntegration消息路由之Router的条件路由与过滤功能》本文详细介绍了Router的基础概念、条件路由实现、基于消息头的路由、动态路由与路由表、消息过滤与选择性路由以及错误处理... 目录引言一、Router基础概念二、条件路由实现三、基于消息头的路由四、动态路由与路由表五、消息过滤

C++ 中的 if-constexpr语法和作用

《C++中的if-constexpr语法和作用》if-constexpr语法是C++17引入的新语法特性,也被称为常量if表达式或静态if(staticif),:本文主要介绍C++中的if-c... 目录1 if-constexpr 语法1.1 基本语法1.2 扩展说明1.2.1 条件表达式1.2.2 fa

Python异步编程中asyncio.gather的并发控制详解

《Python异步编程中asyncio.gather的并发控制详解》在Python异步编程生态中,asyncio.gather是并发任务调度的核心工具,本文将通过实际场景和代码示例,展示如何结合信号量... 目录一、asyncio.gather的原始行为解析二、信号量控制法:给并发装上"节流阀"三、进阶控制

C++中::SHCreateDirectoryEx函数使用方法

《C++中::SHCreateDirectoryEx函数使用方法》::SHCreateDirectoryEx用于创建多级目录,类似于mkdir-p命令,本文主要介绍了C++中::SHCreateDir... 目录1. 函数原型与依赖项2. 基本使用示例示例 1:创建单层目录示例 2:创建多级目录3. 关键注

C++从序列容器中删除元素的四种方法

《C++从序列容器中删除元素的四种方法》删除元素的方法在序列容器和关联容器之间是非常不同的,在序列容器中,vector和string是最常用的,但这里也会介绍deque和list以供全面了解,尽管在一... 目录一、简介二、移除给定位置的元素三、移除与某个值相等的元素3.1、序列容器vector、deque

C++常见容器获取头元素的方法大全

《C++常见容器获取头元素的方法大全》在C++编程中,容器是存储和管理数据集合的重要工具,不同的容器提供了不同的接口来访问和操作其中的元素,获取容器的头元素(即第一个元素)是常见的操作之一,本文将详细... 目录一、std::vector二、std::list三、std::deque四、std::forwa

Redis中高并发读写性能的深度解析与优化

《Redis中高并发读写性能的深度解析与优化》Redis作为一款高性能的内存数据库,广泛应用于缓存、消息队列、实时统计等场景,本文将深入探讨Redis的读写并发能力,感兴趣的小伙伴可以了解下... 目录引言一、Redis 并发能力概述1.1 Redis 的读写性能1.2 影响 Redis 并发能力的因素二、

C++字符串提取和分割的多种方法

《C++字符串提取和分割的多种方法》在C++编程中,字符串处理是一个常见的任务,尤其是在需要从字符串中提取特定数据时,本文将详细探讨如何使用C++标准库中的工具来提取和分割字符串,并分析不同方法的适用... 目录1. 字符串提取的基本方法1.1 使用 std::istringstream 和 >> 操作符示

C++原地删除有序数组重复项的N种方法

《C++原地删除有序数组重复项的N种方法》给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度,不要使用额外的数组空间,你必须在原地修改输入数组并在使用O(... 目录一、问题二、问题分析三、算法实现四、问题变体:最多保留两次五、分析和代码实现5.1、问题分析5.

C++ 各种map特点对比分析

《C++各种map特点对比分析》文章比较了C++中不同类型的map(如std::map,std::unordered_map,std::multimap,std::unordered_multima... 目录特点比较C++ 示例代码 ​​​​​​代码解释特点比较1. std::map底层实现:基于红黑