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/mutex/ below:

public member function

<mutex>

std::unique_lock::mutex
mutex_type* mutex() const noexcept;

Get mutex

Returns a pointer to the managed mutex object.

Note that the unique_lock does not release ownership of the managed mutex object: i.e., if it owns a lock on the mutex, it is still responsible for unlocking it at some point (such as when it is destroyed).

To retrieve and acquire ownership of the managed mutex object see unique_lock::release.



Parameters none

Return value A pointer to the mutex object managed by the unique_lock.

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
30
// unique_lock::mutex example
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::unique_lock, std::defer_lock

class MyMutex : public std::mutex {
  int _id;
public:
  MyMutex (int id) : _id(id) {}
  int id() {return _id;}
};

MyMutex mtx (101);

void print_ids (int id) {
  std::unique_lock<MyMutex> lck (mtx);
  std::cout << "thread #" << id << " locked mutex " << lck.mutex()->id() << '\n';
}

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

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

  return 0;
}

Possible output (order of lines may vary, but they are never intermingled):
thread #2 locked mutex 101
thread #3 locked mutex 101
thread #1 locked mutex 101
thread #4 locked mutex 101
thread #5 locked mutex 101
thread #6 locked mutex 101
thread #7 locked mutex 101
thread #8 locked mutex 101
thread #9 locked mutex 101
thread #10 locked mutex 101


Data races The unique_lock object is accessed.
Its managed mutex object is not accessed by the operation (although a pointer to it is returned).

Exception safetyNo-throw guarantee: never throws exceptions.

See also
unique_lock::release
Release mutex (public member function)
unique_lock::owns_lock
Owns lock (public member function)
unique_lock::operator bool
Return whether it owns a 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