public member function
<mutex>

std::unique_lock::try_lock

bool try_lock();
Lock mutex if not locked
Calls member try_lock of the managed mutex object, and uses the returned value to set the owning state.

If the owning state is already true before the call, or if the object currently manages no mutex object, the function throws a system_error exception.

Parameters

none

Return value

true if the function succeeds in locking the managed mutex object.
false otherwise.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// unique_lock::try_lock example
#include <iostream>       // std::cout
#include <vector>         // std::vector
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::unique_lock, std::defer_lock

std::mutex mtx;           // mutex for critical section

void print_star () {
  std::unique_lock<std::mutex> lck(mtx,std::defer_lock);
  // print '*' if successfully locked, 'x' otherwise: 
  if (lck.try_lock())
    std::cout << '*';
  else                    
    std::cout << 'x';
}

int main ()
{
  std::vector<std::thread> threads;
  for (int i=0; i<500; ++i)
    threads.emplace_back(print_star);

  for (auto& x: threads) x.join();

  return 0;
}


Possible output (the amount of 'x' -if any- may vary):

*****************************x******************************x*x***x***x*x*x**x**
x**********x********************************************************************
************x*x*x*x*************************************************************
*******x********x**********x****************************************************
***************************************x*x*x*x**x*x*x*x*x*x*********************
**x*****************************************************************************
***************x****

Data races

The unique_lock object is accessed/modified.
The managed mutex object is accessed/modified as an atomic operation (causing no data races).

Exception safety

Basic guarantee: if an exception is thrown by this member function, the unique_lock object is left in a valid state.

If the call fails, a system_error exception is thrown:
exception typeerror conditiondescription
system_errorerrc::resource_deadlock_would_occurThe unique_lock object already owns a lock
system_errorerrc::operation_not_permittedThe unique_lock object currently manages no mutex object (because it was default-constructed, moved, or released)
An exception is also thrown if the call to try_lock on the managed mutex object fails, and on any other condition reported with such mechanism by the library implementation.

See also