Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::unique_lock<Mutex>::lock

      From cppreference.com
      <cpp‎ |thread‎ |unique lock
       
       
      Concurrency support library
      Threads
      (C++11)
      (C++20)
      this_thread namespace
      (C++11)
      (C++11)
      (C++11)
      Cooperative cancellation
      Mutual exclusion
      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
       
       
      void lock();
      (since C++11)

      Locks (i.e., takes ownership of) the associated mutex. Effectively callsmutex()->lock().

      Contents

      [edit]Parameters

      (none)

      [edit]Return value

      (none)

      [edit]Exceptions

      • Any exceptions thrown bymutex()->lock().

      [edit]Example

      The following example useslock to re-acquire a mutex that was unlocked.

      Run this code
      #include <chrono>#include <iostream>#include <mutex>#include <thread>#include <vector> int main(){int counter=0;std::mutex counter_mutex;std::vector<std::thread> threads; auto worker_task=[&](int id){std::unique_lock<std::mutex> lock(counter_mutex);++counter;std::cout<< id<<", initial counter: "<< counter<<'\n';        lock.unlock(); // don't hold the lock while we simulate an expensive operationstd::this_thread::sleep_for(std::chrono::seconds(1));         lock.lock();++counter;std::cout<< id<<", final counter: "<< counter<<'\n';}; for(int i=0; i<10;++i)        threads.emplace_back(worker_task, i); for(auto& thread: threads)        thread.join();}

      Possible output:

      0, initial counter: 11, initial counter: 22, initial counter: 33, initial counter: 44, initial counter: 55, initial counter: 66, initial counter: 77, initial counter: 88, initial counter: 99, initial counter: 106, final counter: 113, final counter: 124, final counter: 132, final counter: 145, final counter: 150, final counter: 161, final counter: 177, final counter: 189, final counter: 198, final counter: 20

      [edit]See also

      tries to lock (i.e., takes ownership of) the associated mutex without blocking
      (public member function)[edit]
      unlocks (i.e., releases ownership of) the associated mutex
      (public member function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/thread/unique_lock/lock&oldid=174034"

      [8]ページ先頭

      ©2009-2025 Movatter.jp