当前位置:网站首页>Concurrency - condition variable

Concurrency - condition variable

2022-06-21 09:16:00 Classmate Peng is her deskmate

std::condition_variable

The essence is a class
Generally, it works on :
Threads A: Wait for a condition to be met before running

function

std::condition_variable mcv// Create a condition variable 
std::mutex mtex;// Create a mutex 
vector<int> v;

wait()

If the second parameter is false that wait() Will unlock mutex And block the bank Blocking some other thread to call notify_one() until When in other threads B End of call notify_one() after wait() The thread of A Will be awakened here A Threads do not immediately run the following code Instead, you keep trying to get the mutex lock If it's locked Will judge again wait() Second parameter of
Because in wait() The mutex will be locked before If wait() The second parameter returns false If the mutex is not unlocked You'll get stuck
If you don't write the second parameter The default is false Direct blockage

std::unique_lock<std::mutex>mUniqueTex(mtex);
mcv.wait(mUniqueTex,[]{
    
	if(!v.empty())
		return 	true;
	return false;
})

notify_one()

Try to wake up a wait() The thread of

mcv.notify_one();

notify_all()

Try to wake up all wait() The thread of

mcv.notify_all();
原网站

版权声明
本文为[Classmate Peng is her deskmate]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206210913385643.html