天天看點

C++核心準則CP.21:使用std::lock()或者std::scoped_lock擷取多個mutex

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上發生死鎖。

Example(執行個體)

This is asking for deadlock:

下面的代碼會引發死鎖:

// thread 1
lock_guard<mutex> lck1(m1);
lock_guard<mutex> lck2(m2);

// thread 2
lock_guard<mutex> lck2(m2);
lock_guard<mutex> lck1(m1);      

Instead, use lock():

使用lock代替:

// thread 1
lock(m1, m2);
lock_guard<mutex> lck1(m1, adopt_lock);
lock_guard<mutex> lck2(m2, adopt_lock);

// thread 2
lock(m2, m1);
lock_guard<mutex> lck2(m2, adopt_lock);
lock_guard<mutex> lck1(m1, adopt_lock);      

or (better, but C++17 only):

或者(可以更好,但僅限于C++17)

// thread 1
scoped_lock<mutex, mutex> lck1(m1, m2);

// thread 2
scoped_lock<mutex, mutex> 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的順序上取得一緻,但是順序已經不再重要。

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.

在實際的代碼中,mutex的命名很少能向程式員提示希望的關系和希望的請求次序。在實際的代碼中,mute不會總是在相鄰代碼中執行擷取,那樣的話問題可能更容易被發現。

In C++17 it's possible to write plain

在C++17可以簡單地這樣寫:

lock_guard lck1(m1, adopt_lock);      

and have the mutex type deduced.

這樣就可以實作mutex類型推斷。

Enforcement(實施建議)

Detect the acquisition of multiple mutexes. This is undecidable in general, but catching common simple examples (like the one above) is easy.

檢查多重mutex擷取操作。這一點通常是不可判定的,但是捕捉一般的簡單例子(例如上面的例子)是容易做到的。

原文連結​​https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp21-use-stdlock-or-stdscoped_lock-to-acquire-multiple-mutexes​​

新書介紹

以下是本人3月份出版的新書,拜托多多關注!

C++核心準則CP.21:使用std::lock()或者std::scoped_lock擷取多個mutex

本書利用Python 的标準GUI 工具包tkinter,通過可執行的示例對23 個設計模式逐個進行說明。這樣一方面可以使讀者了解真實的軟體開發工作中每個設計模式的運用場景和想要解決的問題;另一方面通過對這些問題的解決過程進行說明,讓讀者明白在編寫代碼時如何判斷使用設計模式的利弊,并合理運用設計模式。

對設計模式感興趣而且希望随學随用的讀者通過本書可以快速跨越從了解到運用的門檻;希望學習Python GUI 程式設計的讀者可以将本書中的示例作為設計和開發的參考;使用Python 語言進行圖像分析、資料處理工作的讀者可以直接以本書中的示例為基礎,迅速建構自己的系統架構。

繼續閱讀