C++ boost::upgrade_lock upgrade_to_unique_lock 升级锁 是什么 怎么用

Posted 软件工程小施同学

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++ boost::upgrade_lock upgrade_to_unique_lock 升级锁 是什么 怎么用相关的知识,希望对你有一定的参考价值。

upgrade_lock将可将读锁(shared_lock)升级为upgrade_lock,与shared_lock不互斥,与别的upgrade_lock和unique_lock互斥。也就是说线程A获得mutex的upgrade_lock后,线程B、C等还可以获得mutex的share_mutex,反之亦然。

upgrade_to_unique_lock可将upgrade_lock升级为独占锁,不允许其它线程读或写

举例

Read Lock

I need lock positionMutex whenever I’m going to read from memory that this mutex should cover. I do this by using boost::shared_lock() , which allows multiple reads without blocking as long as the mutex hasn’t been upgraded to a unique lock.

boost::shared_lock<boost::shared_mutex> lock(this->positionMutex);


Write Lock

Whenever I write to my position properties, I need to upgrade the mutex to unique access so that other threads don’t read while the new value is being written. This is done by using boost::upgrade_lock  and  boost::upgrade_to_unique_lock as shown below .

boost::upgrade_lock<boost::shared_mutex> lock(this->positionMutex);

boost::upgrade_to_unique_lock<boost::shared_mutex> unique_lock(lock);

https://codersdesiderata.com/2017/04/26/out-of-phase-race-conditions-and-shared-mutexes/

以上是关于C++ boost::upgrade_lock upgrade_to_unique_lock 升级锁 是什么 怎么用的主要内容,如果未能解决你的问题,请参考以下文章

C++ boost锁的概述

C++中对文件的操作

linux C++下的U盘序列号

c++ 转换unicode字符串为js u格式

[C++]语言基础

C++ #elif 指令被丢弃