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++11范围for初始化列表auto decltype详解

《C++11范围for初始化列表autodecltype详解》C++11引入auto类型推导、decltype类型推断、统一列表初始化、范围for循环及智能指针,提升代码简洁性、类型安全与资源管理效... 目录C++11新特性1. 自动类型推导auto1.1 基本语法2. decltype3. 列表初始化3

C++11右值引用与Lambda表达式的使用

《C++11右值引用与Lambda表达式的使用》C++11引入右值引用,实现移动语义提升性能,支持资源转移与完美转发;同时引入Lambda表达式,简化匿名函数定义,通过捕获列表和参数列表灵活处理变量... 目录C++11新特性右值引用和移动语义左值 / 右值常见的左值和右值移动语义移动构造函数移动复制运算符

go动态限制并发数量的实现示例

《go动态限制并发数量的实现示例》本文主要介绍了Go并发控制方法,通过带缓冲通道和第三方库实现并发数量限制,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录带有缓冲大小的通道使用第三方库其他控制并发的方法因为go从语言层面支持并发,所以面试百分百会问到

Go语言并发之通知退出机制的实现

《Go语言并发之通知退出机制的实现》本文主要介绍了Go语言并发之通知退出机制的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录1、通知退出机制1.1 进程/main函数退出1.2 通过channel退出1.3 通过cont

java如何实现高并发场景下三级缓存的数据一致性

《java如何实现高并发场景下三级缓存的数据一致性》这篇文章主要为大家详细介绍了java如何实现高并发场景下三级缓存的数据一致性,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 下面代码是一个使用Java和Redisson实现的三级缓存服务,主要功能包括:1.缓存结构:本地缓存:使

C++中detach的作用、使用场景及注意事项

《C++中detach的作用、使用场景及注意事项》关于C++中的detach,它主要涉及多线程编程中的线程管理,理解detach的作用、使用场景以及注意事项,对于写出高效、安全的多线程程序至关重要,下... 目录一、什么是join()?它的作用是什么?类比一下:二、join()的作用总结三、join()怎么

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

C++中全局变量和局部变量的区别

《C++中全局变量和局部变量的区别》本文主要介绍了C++中全局变量和局部变量的区别,全局变量和局部变量在作用域和生命周期上有显著的区别,下面就来介绍一下,感兴趣的可以了解一下... 目录一、全局变量定义生命周期存储位置代码示例输出二、局部变量定义生命周期存储位置代码示例输出三、全局变量和局部变量的区别作用域

C++中assign函数的使用

《C++中assign函数的使用》在C++标准模板库中,std::list等容器都提供了assign成员函数,它比操作符更灵活,支持多种初始化方式,下面就来介绍一下assign的用法,具有一定的参考价... 目录​1.assign的基本功能​​语法​2. 具体用法示例​​​(1) 填充n个相同值​​(2)

c++ 类成员变量默认初始值的实现

《c++类成员变量默认初始值的实现》本文主要介绍了c++类成员变量默认初始值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录C++类成员变量初始化c++类的变量的初始化在C++中,如果使用类成员变量时未给定其初始值,那么它将被