C++多线程学习[六]: 多线程之间的同步

一、同步问题

实际开发场景中有很多需要同步的情况,例如,音频和视频的同步输出、或者通讯能够第一时间同步接受处理…

二、多线程同步demo

在这里插入图片描述
可以看到cond可以阻塞等待(wait)可以通知一个线程(notify_one)也可以通知所有的线程(notify_all)等等 这里采用的通知一个线程即notify_one。
在这里插入图片描述

#include<iostream>
#include<thread>
#include<mutex>
#include<list>
#include<sstream> //拼接字符串

using namespace std;
condition_variable cond; //通知信号

static mutex mtx;
list<string> mesg;

void ReadTest(int i)
{
	for (;;)
	{
		if (mesg.empty())
		{
			this_thread::sleep_for(10ms);
			continue;
		}
		unique_lock<mutex> lock(mtx);
		cond.wait(lock);
		cout << i<<"thread recive mseg :" << mesg.front() << endl;
		mesg.pop_front();
	}
}
void WriteTest()
{
	int i = 0;
	for (;;)
	{
		this_thread::sleep_for(30ms);
		unique_lock<mutex> lock(mtx);
		stringstream ss;
		ss << "mesg" << i++;
		mesg.push_back(ss.str());
		cond.notify_one();
		cout << "send mesg" << endl;
	}

}
int main() 
{
	thread th(WriteTest);
	th.detach();
	for (int i = 0;i < 3;i++)
	{
		thread th(ReadTest,i+1);
		th.detach();
	}
	getchar();
	return 0;
}

总的来说就是一个线程需要通知其他线程时通过发送通知信号让其他阻塞线程等待接受信号,达成同步的效果。

  • 9
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Rain_ZZX

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值