Multi-threaded lock unlock critical region

Reprinted from https://blog.csdn.net/shaochuang1/article/details/100991407
1.lock and unlock
If the shared data simultaneously read multiple threads, there is no problem. If some thread-shared data read, write some data, the program crashes, we need to prevent this from happening.
Mutex mutex lock and unlock class has two data security can be guaranteed.
:: mutex m_tex std;
m_tex.lock ();
; ... intermediate operating
m_tex.unlock (); //
mutex unlocked the shackles are used in pairs, only this time if there is no lock unlock, to lock the next run when it will stop here, and so run the unlock before they can continue. It must be used in pairs.
Mutex shackles will take some time.

2.lock_guard class is a template, include lock and unlock when in use, to its definition local scope, leaves this scope, it is released at this time will call unlock function, such a method would avoid the unlock forget awkward call.

Published 137 original articles · won praise 5 · views 10000 +

Guess you like

Origin blog.csdn.net/u012719076/article/details/104036506