C++核心准则CP.100:不要使用无锁编程方式,除非绝对必要

时间:2022-07-22
本文章向大家介绍C++核心准则CP.100:不要使用无锁编程方式,除非绝对必要,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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