天天看點

C++核心準則CP.111:如果真的需要好雙重檢查鎖,使用慣用模式

CP.111: Use a conventional pattern if you really need double-checked locking 

CP.111:如果真的需要好雙重檢查鎖,使用慣用模式

Reason(原因)

Double-checked locking is easy to mess up. If you really need to write your own double-checked locking, in spite of the rules CP.110: Do not write your own double-checked locking for initialization and CP.100: Don't use lock-free programming unless you absolutely have to, then do it in a conventional pattern.

雙重檢查鎖容易把事情搞雜。如果你真的需要使用雙重檢查鎖,而不管​​C++核心準則CP.100:不要使用無鎖程式設計方式,除非絕對必要​​​和​​C++核心準則CP.110:不要自已為初始化編寫雙重檢查鎖定代碼​​中的建議,那麼在使用雙重檢查鎖時遵循慣用模式。

The uses of the double-checked locking pattern that are not in violation of CP.110: Do not write your own double-checked locking for initialization arise when a non-thread-safe action is both hard and rare, and there exists a fast thread-safe test that can be used to guarantee that the action is not needed, but cannot be used to guarantee the converse.

當非線程安全動作很難發生,而且存在快速的線程安全測試可以用于保證不需要該動作,但是無法保證相反的情況,可以使用沒有違背​​C++核心準則CP.110:不要自已為初始化編寫雙重檢查鎖定代碼​​準則的雙重檢查鎖模式。

Example, bad(反面示例)

The use of volatile does not make the first check thread-safe, see also CP.200: Use volatile only to talk to non-C++ memory

volatile的使用沒有讓第一個檢查線程安全,參見CP.200:隻在談到非C++記憶體的時候使用volatile

mutex action_mutex;
volatile bool action_needed;

if (action_needed) {
    std::lock_guard<std::mutex> lock(action_mutex);
    if (action_needed) {
        take_action();
        action_needed = false;
    }
}      

Example, good(範例)

mutex action_mutex;
atomic<bool> action_needed;

if (action_needed) {
    std::lock_guard<std::mutex> lock(action_mutex);
    if (action_needed) {
        take_action();
        action_needed = false;
    }
}      

Fine-tuned memory order may be beneficial where acquire load is more efficient than sequentially-consistent load

當順序以執行負載比需求負載更高效時,調整良好的記憶體順序可能更有利

mutex action_mutex;
atomic<bool> action_needed;

if (action_needed.load(memory_order_acquire)) {
    lock_guard<std::mutex> lock(action_mutex);
    if (action_needed.load(memory_order_relaxed)) {
        take_action();
        action_needed.store(false, memory_order_release);
    }
}      

Enforcement(實施建議)

??? Is it possible to detect the idiom?

有可能發現這種慣用法麼?

新書介紹

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

C++核心準則CP.111:如果真的需要好雙重檢查鎖,使用慣用模式

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

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

覺得本文有幫助?請分享給更多人。

關注微信公衆号【面向對象思考】輕松學習每一天!

面向對象開發,面向對象思考!

繼續閱讀