首页 文章详情

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

面向对象思考 | 479 2020-07-27 18:20 0 0 0
UniSMS (合一短信)

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 lock(action_mutex);
if (action_needed) {
take_action();
action_needed = false;
}
}
Example, good(范例)
mutex action_mutex;
atomic action_needed;

if (action_needed) {
std::lock_guard 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 action_needed;

if (action_needed.load(memory_order_acquire)) {
lock_guard 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

新书介绍

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


本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。

对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。




觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!



good-icon 0
favorite-icon 0
收藏
回复数量: 0
    暂无评论~~
    Ctrl+Enter