網(wǎng)站 域名 獨立 一級seo優(yōu)化診斷
c++ 讀寫鎖使用詳解
std::shared_mutex c++17
- 頭文件
#include <shared_mutex>
。 - 用于實現(xiàn)共享和獨占訪問的互斥鎖。
- 提供了一種更加靈活的機制,允許多個線程在共享模式下讀取數(shù)據(jù),但只允許單個線程在獨占模式下寫入或修改數(shù)據(jù)。
- 與 std::mutex 相比,具有以下額外特性:
- 多個線程可以同時以共享模式(shared mode)持有鎖,允許并發(fā)讀取操作。
- 只有一個線程可以以獨占模式(exclusive mode)持有鎖,允許寫入或修改操作。
- 當(dāng)一個線程以獨占模式持有鎖時,其他線程無法以共享模式持有鎖,它們必須等待獨占模式的線程釋放鎖。
- 當(dāng)一個線程以共享模式持有鎖時,其他線程可以以共享模式持有鎖,允許并發(fā)讀取操作。
成員函數(shù)
lock
:鎖定互斥,若互斥不可用則阻塞。try_lock
:嘗試鎖定互斥,若互斥不可用則返回。unlock
:解鎖互斥。lock_shared
:以共享模式鎖定互斥,若互斥不可用則阻塞。try_lock_shared
:嘗試以共享模式鎖定互斥,若互斥不可用則返回。unlock_shared
:解鎖以共享模式鎖定的互斥。
推薦使用方法
- 當(dāng)使用共享模式時,配合 std::shared_lock 使用。
- 當(dāng)使用獨占模式時,配合 std::lock_guard,std::unique_lock 或者 std::scoped_lock 使用。
示例代碼
-
以下示例演示了兩個讀取線程(reader)以共享模式持有 mutex,并同時讀取 shared_data 的值。寫入線程(writer)以獨占模式持有 mutex,并將 shared_data 的值加一。讀取線程可以同時持有鎖,而寫入線程需要等待讀取線程釋放鎖。
#include <cstdio> #include <thread> #include <mutex> #include <shared_mutex>std::shared_mutex mutex; int shared_data = 0;void reader() {std::shared_lock lock(mutex);printf("reader: shared data value is %d\n", shared_data); }void writer() {std::lock_guard lock(mutex);shared_data += 1;printf("writer: incremented shared data value to %d\n", shared_data); }int main() {std::jthread t1(reader);std::jthread t2(writer);std::jthread t3(reader);return 0; }