首页 > 其他分享 >std::condition_variable 条件变量

std::condition_variable 条件变量

时间:2022-08-17 20:44:13浏览次数:54  
标签:std lock void variable include condition

std::condition_variable 条件变量

 

void wait( std::unique_lock<std::mutex>& lock ); #1
template< class Predicate >
void wait( std::unique_lock<std::mutex>& lock, Predicate stop_waiting ); #2

 

例1 :

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

std::mutex m;
std::condition_variable cv;
std::string data;
bool ready = false;
bool processed = false;

void worker_thread()
{
	std::unique_lock lk(m);
	cv.wait(lk, [] { return ready; });

	std::cout << "Worker thread is processing data\n";
	data += " after processing";

	processed = true;
	std::cout << "Worker thread signals data processing completed\n";

	lk.unlock();
	cv.notify_one();
}

int main()
{
	std::thread worker(worker_thread);

	data = "Example data";
	{
		std::lock_guard lk(m);
		ready = true;
		std::cout << "main() signals data ready for processing\n";
	}
	cv.notify_one();

	{
		std::unique_lock lk(m);
		cv.wait(lk, [] { return processed; });
	}
	std::cout << "Back in main(), data = " << data << '\n';

	worker.join();
}

 

标签:std,lock,void,variable,include,condition
From: https://www.cnblogs.com/sunbines/p/16596675.html

相关文章

  • 【python基础】os.listdir乱序问题
    前言想要获取之前某个目录的有序文件,除了文件名称,其他的比如文件内容、创建时间等都发生了改变,不清楚使用os.listdir是否会改变前后的文件排序。可以使用帮助文档查看os.......
  • 一、使用Expected_conditions判断元素是否可见-6
    1、处理定位报错的问题判断该元素存在,再输入。判断该元素不存在,抛出异常。依然是通过EC这个模块。2、判断是否存在邮箱地址,存在,再操作。就不用担心元素不存在,程序......
  • C++ beginner(2)- variable
    initializationintx{};//xisfilledwithzeroes,sox==0intx{123};intx(123);inta,b=123,c{},d{456},e(789);int*x,y,z;==int*x;inty;int......
  • std::string assign
    参考std::string#include<iostream>#include<string>usingnamespacestd;intmain(){stringstr;stringbase="Thequickbrownfoxjumpsoveralazy......
  • SpringBoot-----SpringBoot @Conditional注解自动配置报告
    一、@Conditional简介@Conditional是Spring4新提供的注解,它的作用是按照一定的条件进行判断,满足条件给容器注册Bean。SpringBoot是根据配置文件的内容决定是否创建Bean,以......