Lock in C + +

Source: Internet
Author: User
Tags mutex

@ (C plus plus) [Summary,lock] # Lock in C++11 # # Mutex Wrapper C++11 offers a variety of types of mutex wrapper, mainly with lock_guard,unique_lock and scoped_lock,shared_lock these kinds. Mutexes are rarely used directly, and are often used in conjunction with mutex wrapper. The mutex wrapper uses the RAII mechanism to ensure that the lock is able, even if an exception occurs during lockout. The RAII mechanism has a better explanation on Wikipedia: >resource acquisition is initialization (RAII) are a programming idiom used in several object-oriented languages. In RAII, holding a resource are a class invariant, and is tied to object lifetime:**resource allocation (or acquisition) is done during object creation* * (specifically initialization), by the constructor,**while Resource deallocation (release) is do during object destruction (specifically finalization), by the destructor**. Thus the resource is guaranteed to being held between when initialization finishes and finalization starts (holding the Resou RCEs is a class invariant), and to was held only if the object is alive. Thus If there is no object leaks, there is no resource leaks. # # Lock_guard Lock_guard is the simplest mutex wrapper, providing only' Constructor' AND' destructor' Two interfaces. However, copy constructor is not available. The form of constructor provided is as follows: -Explicit lock_guard (Mutex_type& m); -Lock_guard (Mutex_type& m, std::adopt_lock_t t); -~lock_guard () The member functions supported by lock Guard allow us to summarize its features: -only be able to lock in the constructor, release the lock in the destructor, no lock or unlock interface displayed. -only ADOP can be used_lock_t to inherit the existing lock ownership. Typical two-use scenarios: # # # Ensures the mutex is released correctly "' C + +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 when lockGoes out of scope} ``` # # # Inherits ownership to ensure mutex release "' C + +struct Bank_account {explicit Bank_account (int balance): Balance (balance) {}int balance;Std::mutex m;}; void Transfer (Bank_account &from, bank_account &to, int amount){Lock to ensure that no deadlocks occurStd::lock (FROM.M, TO.M);Lock_guard to ensure that lock is released properly at the endStd::lock_guard<std::mutex> Lock1 (FROM.M, Std::adopt_lock);Std::lock_guard<std::mutex> Lock2 (TO.M, Std::adopt_lock); From.balance-= amount;To.balance + = amount;} ``` # # #unique_lock Unique_lock is also a mutex wrapper, but the function is much richer, mainly reflected in the following aspects: -Allowing deferred locking, -time-constrained attempts at locking, -Recursive locking, -Transfer of lock ownership -Use with condition variables # # # Deferred Locking "' C + +struct Box {explicit Box (int num): num_things{num} {} int num_things;Std::mutex m;}; void Transfer (Box &from, box &to, int num){The lock is not actually acquired at this timeStd::unique_lock<std::mutex> Lock1 (FROM.M, std::d efer_lock);Std::unique_lock<std::mutex> Lock2 (TO.M, std::d efer_lock); Lock both Unique_locks without deadlockStd::lock (Lock1, Lock2); from.num_things-= num;To.num_things + = num; ' FROM.M ' and ' to.m ' mutexes unlocked in ' Unique_lock ' dtors} ``` # # # used for condition variable "' c+Std::mutex m;Std::condition_variable CV;std::string data;BOOL ready = FALSE;BOOL processed = FALSE; void Worker_thread (){Wait until main () sends dataStd::unique_lock<std::mutex> LK (m);Only Unique_lock can be used here, because Unique_lock has external lock and unlock interfacesWait waits with unlock. When awakened, it will lock againCv.wait (LK, []{return ready;}); After the wait, we own the lock.Std::cout << "Worker thread is processing data\n";Data + + "after processing"; Send data back to main ()processed = true;Std::cout << "Worker thread signals data processing completed\n"; Manual unlocking is do before notifying, to avoid waking upThe waiting thread only to block again (see Notify_one for details)Lk.unlock ();Cv.notify_one ();} int main (){Std::thread worker (Worker_thread); data = "Example data";Send data to the worker thread{Std::lock_guard<std::mutex> LK (m);Ready = true;Std::cout << "main () signals data ready for processing\n";}Cv.notify_one (); Wait for the worker{Std::unique_lock<std::mutex> LK (m);Cv.wait (LK, []{return processed;});}Std::cout << "back in Main (), data =" << data << ' \ n '; Worker.join ();} ``` # # Scope_lock ScopeThe _lock function is similar to the Std::lock. In scopeThe _lock constructor gets multiple mutexes, which are locked using algorithm that avoid deadlock, and are unlock in reverse order when they are refactored. * * Note**:std::lock is only responsible for Lock,unlock's work while using the lock_guard or Unique_lock to finish. # # Reference [Std::unique_lock](Http://en.cppreference.com/w/cpp/thread/unique_lock) [Std::scoped_lock](Http://en.cppreference.com/w/cpp/thread/scoped_lock) [std::condition_variable" (http://en.cppreference.com/w/cpp/thread/condition_variable) Span class= "token lf" > [difference between Std::lock_guard and Std::unique_lock http://jakascorner.com/blog/2016/02/ Lock_guard-and-unique_lock.html)

Lock in C + +

Related Article

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.