|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
shared_lock::shared_lock | ||||
| Shared locking | ||||
| Modifiers | ||||
| Observers | ||||
| Non-member functions | ||||
shared_lock()noexcept; | (1) | (since C++14) |
shared_lock( shared_lock&& other)noexcept; | (2) | (since C++14) |
explicit shared_lock( mutex_type& m); | (3) | (since C++14) |
shared_lock( mutex_type& m,std::defer_lock_t t)noexcept; | (4) | (since C++14) |
shared_lock( mutex_type& m,std::try_to_lock_t t); | (5) | (since C++14) |
shared_lock( mutex_type& m,std::adopt_lock_t t); | (6) | (since C++14) |
template<class Rep,class Period> shared_lock( mutex_type& m, | (7) | (since C++14) |
template<class Clock,class Duration> shared_lock( mutex_type& m, | (8) | (since C++14) |
Constructs ashared_lock, optionally locking the supplied mutex.
shared_lock with no associated mutex.shared_lock with the contents ofother. Leavesother with no associated mutex.shared_lock withm as the associated mutex. Additionally:lock_shared,try_lock_shared,try_lock_shared_for, ortry_lock_shared_until) onm. The behavior is undefined if not so.Mutex does not meet theSharedTimedLockable requirements.Mutex does not meet theSharedTimedLockable requirements.| other | - | anothershared_lock to initialize the state with |
| m | - | mutex to associate with the lock and optionally acquire ownership of |
| t | - | tag parameter used to select constructors with different locking strategies |
| timeout_duration | - | maximum duration to block for |
| timeout_time | - | maximum time point to block until |
#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){// both the threads get access to the integer istd::shared_lock<std::shared_timed_mutex> slk(m);constint ii= i;// reads global 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();}
Possible output:
#2 read i as 10...#1 read i as 10...#2 woke up...#1 woke up...