Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::shared_mutex

      From cppreference.com
      <cpp‎ |thread
       
       
      Concurrency support library
      Threads
      (C++11)
      (C++20)
      this_thread namespace
      (C++11)
      (C++11)
      (C++11)
      Cooperative cancellation
      Mutual exclusion
      (C++11)
      shared_mutex
      (C++17)
      Generic lock management
      (C++11)
      (C++11)
      (C++11)
      (C++11)
      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
       
       
      Defined in header<shared_mutex>
      class shared_mutex;
      (since C++17)

      Theshared_mutex class is a synchronization primitive that can be used to protect shared data from being simultaneously accessed by multiple threads. In contrast to other mutex types which facilitate exclusive access, a shared_mutex has two levels of access:

      • shared - several threads can share ownership of the same mutex.
      • exclusive - only one thread can own the mutex.

      If one thread has acquired theexclusive lock (throughlock,try_lock), no other threads can acquire the lock (including theshared).

      If one thread has acquired theshared lock (throughlock_shared,try_lock_shared), no other thread can acquire theexclusive lock, but can acquire theshared lock.

      Only when theexclusive lock has not been acquired by any thread, theshared lock can be acquired by multiple threads.

      Within one thread, only one lock (shared orexclusive) can be acquired at the same time.

      Shared mutexes are especially useful when shared data can be safely read by any number of threads simultaneously, but a thread may only write the same data when no other thread is reading or writing at the same time.

      Theshared_mutex class satisfies all requirements ofSharedMutex andStandardLayoutType.

      Contents

      [edit]Member types

      Member type Definition
      native_handle_type(optional*) implementation-defined[edit]

      [edit]Member functions

      constructs the mutex
      (public member function)[edit]
      destroys the mutex
      (public member function)[edit]
      operator=
      [deleted]
      not copy-assignable
      (public member function)[edit]
      Exclusive locking
      locks the mutex, blocks if the mutex is not available
      (public member function)[edit]
      tries to lock the mutex, returns if the mutex is not available
      (public member function)[edit]
      unlocks the mutex
      (public member function)[edit]
      Shared locking
      locks the mutex for shared ownership, blocks if the mutex is not available
      (public member function)[edit]
      tries to lock the mutex for shared ownership, returns if the mutex is not available
      (public member function)[edit]
      unlocks the mutex (shared ownership)
      (public member function)[edit]
      Native handle
      returns the underlying implementation-defined native handle object
      (public member function)[edit]

      [edit]Example

      The output below was generated on a single-core machine. Whenthread1 starts, it enters the loop for the first time and callsincrement() followed byget(). However, before it can print the returned value tostd::cout, the scheduler putsthread1 to sleep and wakes upthread2, which obviously has time enough to run all three loop iterations at once. Back tothread1, still in the first loop iteration, it finally prints its local copy of the counter's value, which is1, tostd::cout and then runs the remaining two loop iterations. On a multi-core machine, none of the threads is put to sleep and the output is more likely to be in ascending order.

      Run this code
      #include <iostream>#include <mutex>#include <shared_mutex>#include <syncstream>#include <thread> class ThreadSafeCounter{public:    ThreadSafeCounter()=default; // Multiple threads/readers can read the counter's value at the same time.unsignedint get()const{std::shared_lock lock(mutex_);return value_;} // Only one thread/writer can increment/write the counter's value.void increment(){std::unique_lock lock(mutex_);++value_;} // Only one thread/writer can reset/write the counter's value.void reset(){std::unique_lock lock(mutex_);        value_=0;} private:    mutable std::shared_mutex mutex_;unsignedint value_{};}; int main(){    ThreadSafeCounter counter; auto increment_and_print=[&counter](){for(int i{}; i!=3;++i){            counter.increment();std::osyncstream(std::cout)<<std::this_thread::get_id()<<' '<< counter.get()<<'\n';}}; std::thread thread1(increment_and_print);std::thread thread2(increment_and_print);     thread1.join();    thread2.join();}

      Possible output:

      123084176803584 2123084176803584 3123084176803584 4123084185655040 1123084185655040 5123084185655040 6

      [edit]See also

      provides shared mutual exclusion facility and implements locking with a timeout
      (class)[edit]
      implements movable shared mutex ownership wrapper
      (class template)[edit]
      implements movable mutex ownership wrapper
      (class template)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/thread/shared_mutex&oldid=153276"

      [8]ページ先頭

      ©2009-2025 Movatter.jp