C++学习0.1: 条件变量

0.引用:

C++条件变量_c++ 条件变量-优快云博客

1.正文

条件变量的使用,其实是一种多线程通知模式,当线程一使用完数据后,通过条件变量通知其他线程,C++11后开始支持。

说明

条件变量必须配合mutex使用,确保并发访问的排他性

std::unique_lock<std::mutex> lock(m);

 线程让自我挂起,释放锁, 等待条件匹配

若next == index为false则线程挂起,释放锁,直到被唤醒;唤醒后再判断next == index,若为false则继续挂起,直到被唤醒同时条件为true。

 

 cv.wait(lock, [=]{return next == index; });
    ...

发送通知以唤醒等待队列中所有线程

 

cv.notify_all();

主线程等待线程结束

t.join

其他条件变量函数 


notify_one                    通知一个等待的线程
notify_all                      通知所有等待的线程
wait                              阻塞当前线程,直到条件变量被唤醒
wait_for                        阻塞当前线程,直到条件变量被唤醒,或到指定时限时长后
wait_until                      阻塞当前线程,直到条件变量被唤醒,或直到抵达指定时间点
native_handle               返回原生句柄

测试代码:

#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>

std::mutex m;
std::condition_variable cv;
std::vector<int> result;
int next = 0;

void worker(int index)
{
	for(int i=0;  i<10; i++)
	{
		//get mutex lock
		std::unique_lock<std::mutex> lock(m);
		//condition waith with mutex lock hold
		cv.wait(lock, [=]{return next == index;});
		std::cout << "workder" << index << std::endl;
		result.push_back(index);
		next = next + 1;
		if(next > 2)
		{
			next = 1;
		}
		cv.notify_all();
	}
}

int main(int argc, char *argv[])
{
	std::thread worker1(worker, 1);
	std::thread worker2(worker, 2);
	{
		std::lock_guard<std::mutex> l(m);
		next = 1;
	}
	std::cout << "Start\n";
	cv.notify_all();
	worker1.join();
	worker2.join();

	for(auto e : result)
	{
		std::cout << e << ' ';
	}
	std::cout << std::endl;
}

2.结果:

3.源码分析

4.实验结果经验和总结:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值