CP.100: Don't use lock-free programming unless you absolutely have to
CP.100:不要使用无锁编程方式,除非绝对必要
Reason(原因)
It's error-prone and requires expert level knowledge of language features, machine architecture, and data structures.
这种方式容易出错,需要在语言功能,机器架构,数据结构等方面具有专家级的知识。
Example, bad(反面示例)
extern atomic<Link*> head; // the shared head of a linked list
Link* nh = new Link(data, nullptr); // make a link ready for insertion
Link* h = head.load(); // read the shared head of the list
do {
if (h->data <= data) break; // if so, insert elsewhere
nh->next = h; // next element is the previous head
} while (!head.compare_exchange_weak(h, nh)); // write nh to head or to h
Spot the bug. It would be really hard to find through testing. Read up on the ABA problem.
找到bug。这里的问题真的很难通过测试发现。好好研究一下ABA问题。
ABA问题参考链接:https://www.cnblogs.com/demian/p/11141733.html
Exception(例外)
Atomic variables can be used simply and safely, as long as you are using the sequentially consistent memory model (memory_order_seq_cst), which is the default.
原子变量可以简单并安全地使用,只要你使用的是顺序一致内存模型(memory_order_seq_cst),这是默认的前提。
Note(注意)
Higher-level concurrency mechanisms, such as threads and mutexes are implemented using lock-free programming.
Alternative: Use lock-free data structures implemented by others as part of some library.
高级的并发机制,例如线程和互斥锁是通过无锁编程实现的。
其他选项:使用由其他人实现的作为某些库一部分存在的无锁编程数据结构。
原文链接https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#cp61-use-async-to-spawn-concurrent-tasks
新书介绍
以下是本人3月份出版的新书,拜托多多关注!
本书利用Python 的标准GUI 工具包tkinter,通过可执行的示例对23 个设计模式逐个进行说明。这样一方面可以使读者了解真实的软件开发工作中每个设计模式的运用场景和想要解决的问题;另一方面通过对这些问题的解决过程进行说明,让读者明白在编写代码时如何判断使用设计模式的利弊,并合理运用设计模式。
对设计模式感兴趣而且希望随学随用的读者通过本书可以快速跨越从理解到运用的门槛;希望学习Python GUI 编程的读者可以将本书中的示例作为设计和开发的参考;使用Python 语言进行图像分析、数据处理工作的读者可以直接以本书中的示例为基础,迅速构建自己的系统架构。
觉得本文有帮助?请分享给更多人。
关注微信公众号【面向对象思考】轻松学习每一天!
面向对象开发,面向对象思考!