前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C++核心准则CP.100:不要使用无锁编程方式,除非绝对必要

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

作者头像
面向对象思考
发布2020-07-17 15:11:38
6220
发布2020-07-17 15:11:38
举报

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(反面示例)

代码语言:javascript
复制
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

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2020-07-16,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 面向对象思考 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • CP.100: Don't use lock-free programming unless you absolutely have to
  • Reason(原因)
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档