[c++11 concurrent programming] The basic operation of the Mutex

Source: Internet
Author: User

Mutexes are one of the most common data protection mechanisms in C + +, and before accessing a piece of shared data, the lock mutex unlock the mutex after it has completed access to the data. Line libraries When a particular mutex is locked by a thread, the other thread that tries to lock the same mutex will be suspended to instruct the mutex to be unlock. This ensures that the data that all threads see is intact and will not be modified by a portion of the data.


In C + +, we typically get a mutex by creating an instance of Std::mutex, calling its member function lock () to lock it, calling unlock to unlock it, but it is not recommended when actually implemented, because it requires us to remember all the calls unlock () Branch of code, including the exception branch. The C + + standard library provides the Std::lock_guard template class, which locks the mutex in the constructor, unlocks it in the destructor, and the following is an instance of a linked list that uses Std::lock_guard to protect the access of multiple threads.


#include "stdafx.h" #include <list> #include <mutex> #include <algorithm>//global variable list std::list<int > some_list;//global variable Mutexstd::mutex some_mutex;void add_to_list (int new_value) {//use Lock_guard to protect linked list Std::lock_guard <std::mutex> Guard (Some_mutex); Some_list.push_back (New_value);} BOOL List_contains (int value_to_find) {//Use Lock_guard to protect the linked list Std::lock_guard<std::mutex> guard (Some_mutex); Return Std::find (Some_list.begin (), Some_list.end (), value_to_find)! = Some_list.end ();} #include <iostream>int main () {add_to_list) Std::cout << "contains (1) =" << list_contains (1) < < ", contains =" << list_contains << Std::endl;}

In general, it is better to have mutexes, Add_to_list, and list_contains as member variables and member functions of a class than as global variables, because the mutex is more relevant to the data it is protecting. When you add other member functions to access shared data, you also need to create lock_guard instances in these newly added functions. However, it is important to note that if a member function returns a pointer or reference to a shared data, it can cause the protected data to be accidentally accessed or modified, and should be avoided when designing the interface.


The following example is an example of a risk caused by giving the protected data to a user-defined function:

#include <mutex>class some_data{int a;std::string b;public:void do_something () {}};class data_wrapper{private: Some_data Data;std::mutex m;public:template<typename function>void process_data (Function func) {Std::lock_ Guard<std::mutex> L (m); func (data);}}; some_data* unprotected;void malicious_function (some_data& protected_data) {unprotected = &protected_data;} Data_wrapper x;void foo () {x.process_data (malicious_function); unprotected->do_something ();} int main () {foo ();}
In this case, Process_data Kan looks fine, it uses Std::lock_gurad to protect the data, but invoking the user-defined function func means that Foo can pass in the Malicious_function to bypass the protection and call Do_ Something () does not perform a lock operation on the data. More than that, there are other issues with this code, such as the call to Unprotected->do_something () in Foo () and the need to lock the data. Performing a lock operation on the right mutex is what all programmers need to do, and the basic criteria are:

Do not pass pointers or references to protected data outside of the lock control range, for example, by returning values from functions, using additional pointers or references to store protected data or passing them as parameters to other functions.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

[c++11 concurrent programming] The basic operation of the Mutex

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.