Namespaces
Variants

std::shared_lock<Mutex>:: shared_lock

From cppreference.net
Concurrency support library
Threads
(C++11)
(C++20)
this_thread namespace
(C++11)
(C++11)
Cooperative cancellation
Mutual exclusion
Generic lock management
Condition variables
(C++11)
Semaphores
Latches and Barriers
(C++20)
(C++20)
Futures
(C++11)
(C++11)
(C++11)
Safe reclamation
Hazard pointers
Atomic types
(C++11)
(C++20)
Initialization of atomic types
(C++11) (deprecated in C++20)
(C++11) (deprecated in C++20)
Memory ordering
(C++11) (deprecated in C++26)
Free functions for atomic operations
Free functions for atomic flags
shared_lock ( ) noexcept ;
(1) (自 C++14 起)
shared_lock ( shared_lock && other ) noexcept ;
(2) (自 C++14 起)
explicit shared_lock ( mutex_type & m ) ;
(3) (自 C++14 起)
shared_lock ( mutex_type & m, std:: defer_lock_t t ) noexcept ;
(4) (自 C++14 起)
shared_lock ( mutex_type & m, std:: try_to_lock_t t ) ;
(5) (自 C++14 起)
shared_lock ( mutex_type & m, std:: adopt_lock_t t ) ;
(6) (自 C++14 起)
template < class Rep, class Period >

shared_lock ( mutex_type & m,

const std:: chrono :: duration < Rep,Period > & timeout_duration ) ;
(7) (自 C++14 起)
template < class Clock, class Duration >

shared_lock ( mutex_type & m,

const std:: chrono :: time_point < Clock,Duration > & timeout_time ) ;
(8) (自 C++14 起)

构造一个 shared_lock ,可选择性地锁定提供的互斥量。

1) 构造一个没有关联互斥量的 shared_lock
2) 移动构造函数。使用 other 的内容初始化 shared_lock 。使 other 不再关联任何互斥量。
3-8) 构造一个以 m 作为关联互斥量的 shared_lock 。此外:
3) 通过调用 m. lock_shared ( ) 以共享模式锁定关联的互斥量。
4) 不会锁定关联的互斥量。
5) 尝试以共享模式非阻塞地锁定关联互斥锁,通过调用 m. try_lock_shared ( )
6) 假定调用线程已持有共享锁(即通过 lock_shared try_lock_shared try_lock_shared_for try_lock_shared_until 获取的锁)作用于 m 。若非如此,则行为未定义。
7) 尝试通过调用 m. try_lock_shared_for ( timeout_duration ) 以共享模式锁定关联的互斥量,该调用将阻塞直到指定的 timeout_duration 时间耗尽或获得锁(以先到者为准)。可能阻塞时间会超过 timeout_duration 。若 Mutex 不满足 SharedTimedLockable 要求,则行为未定义。
8) 尝试通过调用 m. try_lock_shared_until ( timeout_time ) 以共享模式锁定关联的互斥量,该调用将阻塞直到指定的 timeout_time 时间到达或获得锁(以先到者为准)。可能阻塞时间会超过 timeout_time 所指定的时间点。如果 Mutex 不满足 SharedTimedLockable 要求,则行为未定义。

参数

other - 用于初始化状态的另一个 shared_lock
m - 要与此锁关联并可选择获取所有权的互斥量
t - 用于选择具有不同锁定策略的构造函数的标签参数
timeout_duration - 阻塞的最大持续时间
timeout_time - 阻塞截止的最大时间点

示例

#include <chrono>
#include <iostream>
#include <shared_mutex>
#include <syncstream>
#include <thread>
std::shared_timed_mutex m;
int i = 10;
void read_shared_var(int id)
{
     // 两个线程都能访问整型变量 i
     std::shared_lock<std::shared_timed_mutex> slk(m);
     const int ii = i; // 读取全局变量 i
     std::osyncstream(std::cout) << '#' << id << " read i as " << ii << "...\n";
     std::this_thread::sleep_for(std::chrono::milliseconds(10));
     std::osyncstream(std::cout) << '#' << id << " woke up..." << std::endl;
}
int main()
{
     std::thread r1{read_shared_var, 1};
     std::thread r2{read_shared_var, 2};
     r1.join();
     r2.join();
}

可能的输出:

#2 read i as 10...
#1 read i as 10...
#2 woke up...
#1 woke up...