public member function
<mutex>

std::unique_lock::unlock

void unlock();
Unlock mutex
Calls member unlock of the managed mutex object, and sets the owning state to false.

If the owning state is false before the call, the function throws a system_error exception with operation_not_permitted as error condition.

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

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

void print_thread_id (int id) {
  std::unique_lock<std::mutex> lck (mtx,std::defer_lock);
  // critical section (exclusive access to std::cout signaled by locking lck):
  lck.lock();
  std::cout << "thread #" << id << '\n';
  lck.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 unique_lock object is modified.
The managed mutex object is accessed and 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::operation_not_permittedThe unique_lock object currently manages no mutex object (because it was default-constructed, moved, or released)
Depending on the library implementation, this member function may also throw exceptions to report other situations.

See also