Original: Http://en.cppreference.com/w/cpp/thread/lock_guard
Std::lock_guard
The Lock_guard class is a mutex wrapper that provides a convenient RAII style mechanism for owning one or more mutexes. (
the so-called RAII is called resource acquisition is initialization, and Chinese is "initialization of resource acquisition". But the literal translation does not explain the meaning of the phrase very well. In fact, the meaning is not highly complex, in short, when the resource acquisition is encapsulated in a class of object, the use of "stack resources will be at the end of the lifecycle of the corresponding object automatically destroyed" to automatically release resources, that is, the release of resources in the destructor. So this raii is actually similar to the implementation of the smart pointer. )
When a Lock_guard object is created, it attempts to acquire ownership of the mutex given to it. When control is not in the range that the Lock_guard object was created in, the Lock_guard is destructor, and the mutex is freed.
If a few mutexes are given, the deadlock avoidance algorithm is used, such as Std::lock. (Since c++17)
The Lock_guard class is non-copyable.
Sample programs:
#include <thread>
#include <mutex>
#include <iostream>
int g_i = 0;
Std::mutex G_i_mutex; Protects g_i
void safe_increment ()
{
std::lock_guard<std::mutex> lock (G_i_mutex);
++g_i;
Std::cout << std::this_thread::get_id () << ":" << g_i << ' \ n ';
G_i_mutex is automatically released as lock goes out of scope
}
int main ()
{
Std::cout << _ _func__ << ":" << g_i << ' \ n ';
Std::thread T1 (safe_increment);
Std::thread T2 (safe_increment);
T1.join ();
T2.join ();
Std::cout << __func__ << ":" << g_i << ' \ n ';
}
Possible output:
main:0
140641306900224:1
140641298507520:2
Main:2