public member function
<mutex>

std::lock_guard::lock_guard

locking (1)
explicit lock_guard (mutex_type& m);
adopting (2)
lock_guard (mutex_type& m, adopt_lock_t tag);
copy [deleted](3)
lock_guard (const lock_guard&) = delete;
Construct lock_guard
Constructs a lock_guard object that keeps m locked.

(1) locking initialization
The object manages m, and locks it (by calling m.lock()).
(2) adopting initialization
The object manages m, which is a mutex object currently locked by the constructing thread.
(3) copy construction
Deleted (lock_guard objects cannot be copied/moved).

The object keeps m locked and maintains a reference to it, which is used to unlock it on destruction (by calling its member unlock).

Parameters

m
mutex object to be managed by the lock_guard object.
mutex_type is lock_guard's template parameter (the type of the owned mutex object).
tag
This tag argument is merely used to select a specific constructor (values of these types have no state).
It is one of the following values:
argument valuedescription
(no tag)Lock on construction by calling member lock automatically.
adopt_lockAdopt current lock (assume it is already locked by thread).
adopt_lock_t is the type of object adopt_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
// constructing lock_guard with adopt_lock
#include <iostream>       // std::cout
#include <thread>         // std::thread
#include <mutex>          // std::mutex, std::lock_guard, std::adopt_lock

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

void print_thread_id (int id) {
  mtx.lock();
  std::lock_guard<std::mutex> lck (mtx, std::adopt_lock);
  std::cout << "thread #" << id << '\n';
}

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

Argument m may be accessed or modified (as an atomic operation, causing no data races).
The object keeps a reference to m, which is modified on destruction.

Exception safety

For the locking version (1), if m is not currently locked by the calling thread, the constructor never throws exceptions (no-throw guarantee).
For the adopting version (2), if m is currently locked by the calling thread, the constructor never throws exceptions (no-throw guarantee).
Otherwise, it causes undefined behavior.

See also