C++的并发世界(九)——条件变量

0.绪论——单例模型

  单例设计模式是一种常见的设计模式,用于确保某个类只能创建一个实例。由于单例实例是全局唯一的。因此在多线程环境中使用单例模式时,需要考虑线程安全的问题。

1.消费者设计模式

在这里插入图片描述

2.condition_variable使用步骤

①准备好信号量

std::condition_variable cv;

②获取mutex
③获取mutex时修改数据
④释放锁并通知读取线程

lock.unlock();
cv.notify_one();
cv.notify_all();

3.读取共享变量的线程步骤

①获取与改变共享变量线程共同的mutex;
②等待信号通知 Wait()函数

4.condition_variable使用案例

#include <iostream>
#include <string>
#include <thread>
#include <list>
#include <sstream>
#include <mutex>

std::list<std::string> message;
std::mutex mux;
std::condition_variable cv;

void ThreadWrite()
{
	for (int i = 0;; i++)
	{
		std::stringstream ss;
		ss << "Write msg" << i;
		std::unique_lock<std::mutex> lock(mux);
		message.push_back(ss.str());
		lock.unlock();
		cv.notify_one();//发送信号
		std::this_thread::sleep_for(std::chrono::seconds(100));
	}
}

void ThreadRead(int i)
{
	for (;;)
	{
		std::cout << "read msg:" << " [in] " << i <<std::endl;
		std::unique_lock<std::mutex> lock(mux);
		cv.wait(lock);//阻塞扽得改信号
	
		while (!message.empty())
		{
			std::cout << i << "read:" << message.front() << std::endl;
			message.pop_front();
		}
	}
}

int main()
{ 
	std::thread th(ThreadWrite);
	th.detach();

	for (int i = 0; i < 3; i++)
	{
		std::thread th(ThreadRead,i + 1);
		th.detach();
	}

	getchar();
	return 0;
}

相关推荐

  1. Golang 并发 Cond条件变量

    2024-04-09 12:40:01       59 阅读
  2. C++ 并发编程 | 并发世界

    2024-04-09 12:40:01       64 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-09 12:40:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-09 12:40:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-09 12:40:01       87 阅读
  4. Python语言-面向对象

    2024-04-09 12:40:01       96 阅读

热门阅读

  1. 从零开始精通RTSP之初识实时流协议

    2024-04-09 12:40:01       40 阅读
  2. 计算机网络---第三天

    2024-04-09 12:40:01       34 阅读
  3. SpringBoot通过token实现用户互踢功能

    2024-04-09 12:40:01       36 阅读
  4. C++:万能进制转换

    2024-04-09 12:40:01       41 阅读
  5. iOS MT19937随机数生成,结合AES-CBC加密算法实现。

    2024-04-09 12:40:01       28 阅读
  6. 头歌:共享单车之数据可视化

    2024-04-09 12:40:01       39 阅读
  7. 计算机网络-ICMP和ARP协议——沐雨先生

    2024-04-09 12:40:01       38 阅读
  8. Ubuntu22.04 安装 Supabase

    2024-04-09 12:40:01       34 阅读
  9. 【力扣】238. 除自身以外数组的乘积

    2024-04-09 12:40:01       42 阅读
  10. npm的一些经常使用的命令

    2024-04-09 12:40:01       38 阅读