C++核心准则CP.111:如果真的需要好双重检查锁,使用惯用模式

时间:2022-07-22
本文章向大家介绍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?

有可能发现这种惯用法么?

原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp110-do-not-write-your-own-double-checked-locking-for-initialization