A RetroSearch Logo

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

Search Query:

Showing content from https://cplusplus.com/reference/mutex/unique_lock/owns_lock/ below:

public member function

<mutex>

std::unique_lock::owns_lock
bool owns_lock() const noexcept;

Owns lock

Returns whether the object owns a lock.

This is true if the managed mutex object was locked (or adopted) by the unique_lock object, and hasn't been unlocked or released since.

In all other cases, it is false.

This is an alias of unique_lock::operator bool.



Parameters none

Return valuetrue is the object owns a lock on 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::operator= example
#include <iostream>       // std::cout
#include <vector>         // std::vector
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::unique_lock, std::try_to_lock

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

void print_star () {
  std::unique_lock<std::mutex> lck(mtx,std::try_to_lock);
  // print '*' if successfully locked, 'x' otherwise: 
  if (lck.owns_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****************


Data races The unique_lock object is accessed.
Its managed mutex object is not accessed by the operation.

Exception safetyNo-throw guarantee: never throws exceptions.

See also
unique_lock::mutex
Get mutex (public member function)
unique_lock::unlock
Unlock mutex (public member function)
unique_lock::~unique_lock
Destroy unique_lock (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