C++核心準(zhǔn)則CP.21:使用std::lock()或者std::scoped_lock獲取多個...

CP.21: Use?std::lock()?or?std::scoped_lock?to acquire multiple?mutexes
CP.21:使用std::lock()或者std::scoped_lock獲取多個mutex
Reason(原因)
To avoid deadlocks on multiple?mutexes.
避免在多個mutex上發(fā)生死鎖。
Example(實(shí)例)
This is asking for deadlock:
下面的代碼會引發(fā)死鎖:
// thread 1
lock_guard lck1(m1);
lock_guard lck2(m2);
// thread 2
lock_guard lck2(m2);
lock_guard lck1(m1);
Instead, use?lock():
使用lock代替:
// thread 1
lock(m1, m2);
lock_guard lck1(m1, adopt_lock);
lock_guard lck2(m2, adopt_lock);
// thread 2
lock(m2, m1);
lock_guard lck2(m2, adopt_lock);
lock_guard lck1(m1, adopt_lock);
or (better, but C++17 only):
或者(可以更好,但僅限于C++17)
// thread 1
scoped_lock lck1(m1, m2);
// thread 2
scoped_lock lck2(m2, m1);
Here, the writers of?thread1?and?thread2?are still not agreeing on the order of the?mutexes, but order no longer matters.
這里,thread1和thread2的作者仍然沒有在獲取mutex的順序上取得一致,但是順序已經(jīng)不再重要。
Note(注意)
In real code,?mutexes are rarely named to conveniently remind the programmer of an intended relation and intended order of acquisition. In real code,?mutexes are not always conveniently acquired on consecutive lines.
在實(shí)際的代碼中,mutex的命名很少能向程序員提示希望的關(guān)系和希望的請求次序。在實(shí)際的代碼中,mute不會總是在相鄰代碼中執(zhí)行獲取,那樣的話問題可能更容易被發(fā)現(xiàn)。
In C++17 it's possible to write plain
在C++17可以簡單地這樣寫:
lock_guard lck1(m1, adopt_lock);
and have the?mutex?type deduced.
這樣就可以實(shí)現(xiàn)mutex類型推斷。
Enforcement(實(shí)施建議)
Detect the acquisition of multiple?mutexes. This is undecidable in general, but catching common simple examples (like the one above) is easy.
檢查多重mutex獲取操作。這一點(diǎn)通常是不可判定的,但是捕捉一般的簡單例子(例如上面的例子)是容易做到的。
原文鏈接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp21-use-stdlock-or-stdscoped_lock-to-acquire-multiple-mutexes
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
