A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://cplusplus.com/mutex::try_lock below:

public member function

<mutex>

std::mutex::try_lock

Lock mutex if not locked

Attempts to lock the mutex, without blocking:

This function may fail spuriously when no other thread has a lock on the mutex, but repeated calls in these circumstances shall succeed at some point.

All lock and unlock operations on the mutex follow a single total order, with all visible effects synchronized between the lock operations and previous unlock operations on the same object.



Parameters none

Return valuetrue if the function succeeds in locking the mutex for the thread.
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
28
29
// mutex::try_lock example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex

volatile int counter (0); // non-atomic counter
std::mutex mtx;           // locks access to counter

void attempt_10k_increases () {
  for (int i=0; i<10000; ++i) {
    if (mtx.try_lock()) {   // only increase if currently not locked:
      ++counter;
      mtx.unlock();
    }
  }
}

int main ()
{
  std::thread threads[10];
  // spawn 10 threads:
  for (int i=0; i<10; ++i)
    threads[i] = std::thread(attempt_10k_increases);

  for (auto& th : threads) th.join();
  std::cout << counter << " successful increases of the counter.\n";

  return 0;
}

Possible output (any count between 1 and 100000 possible):
80957 successful increases of the counter.


Data races The mutex object is accessed/modified as an atomic operation (causes no data races).

Exception safety If the mutex isn't currently locked by the calling thread, this function never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.

See also
mutex::lock
Lock mutex (public member function)
mutex::unlock
Unlock mutex (public member function)

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4