<mutex>

public member function
<mutex>

std::mutex::unlock

void unlock();
Unlock mutex
Unlocks the mutex, releasing ownership over it.

If other threads are currently blocked attempting to lock this same mutex, one of them acquires ownership over it and continues its execution.

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.

If the mutex is not currently locked by the calling thread, it causes undefined behavior.

Parameters

none

Return value

none

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
// mutex::lock/unlock
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex

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

void print_thread_id (int id) {
  // critical section (exclusive access to std::cout signaled by locking mtx):
  mtx.lock();
  std::cout << "thread #" << id << '\n';
  mtx.unlock();
}

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

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

  return 0;
}


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

Data races

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

Exception safety

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

See also