C++11 Multi-thread Std::lock_guard

Source: Internet
Author: User
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



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.