Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      std::recursive_mutex::try_lock

      From cppreference.com
      <cpp‎ |thread‎ |recursive mutex

      [edit template]
       
       
      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
       
       
      bool try_lock()noexcept;
      (since C++11)

      Tries to lock the mutex. Returns immediately. On successful lock acquisition returnstrue, otherwise returnsfalse.

      This function is allowed to fail spuriously and returnfalse even if the mutex is not currently locked by any other thread.

      A thread may calltry_lock on a recursive mutex repeatedly. Successful calls totry_lock increment the ownership count: the mutex will only be released after the thread makes a matching number of calls tounlock.

      The maximum number of levels of ownership is unspecified. A call totry_lock will returnfalse if this number is exceeded.

      Priorunlock() operation on the same mutexsynchronizes-with (as defined instd::memory_order) this operation if it returnstrue. Note that priorlock() does not synchronize with this operation if it returnsfalse.

      Contents

      [edit]Parameters

      (none)

      [edit]Return value

      true if the lock was acquired successfully, otherwisefalse.

      [edit]Exceptions

      Throws nothing.

      [edit]Example

      [edit]
      Run this code
      #include <iostream>#include <mutex> int main(){std::recursive_mutex test;if(test.try_lock()){std::cout<<"lock acquired\n";        test.unlock();}elsestd::cout<<"lock not acquired\n";     test.lock();// non-recursive mutex would return false from try_lock nowif(test.try_lock()){std::cout<<"lock acquired\n";        test.unlock();}elsestd::cout<<"lock not acquired\n";     test.unlock();}

      Output:

      lock acquiredlock acquired

      [edit]See also

      locks the mutex, blocks if the mutex is not available
      (public member function)[edit]
      unlocks the mutex
      (public member function)[edit]
      C documentation formtx_trylock
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=cpp/thread/recursive_mutex/try_lock&oldid=132347"

      [8]ページ先頭

      ©2009-2025 Movatter.jp