C++中为什么不要使用无锁编程方式

发布时间:2021-11-25 15:45:13 作者:iii
来源:亿速云 阅读:266

这篇文章主要介绍“C++中为什么不要使用无锁编程方式”,在日常操作中,相信很多人在C++中为什么不要使用无锁编程方式问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”C++中为什么不要使用无锁编程方式”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

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问题。

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.

高级的并发机制,例如线程和互斥锁是通过无锁编程实现的。

其他选项:使用由其他人实现的作为某些库一部分存在的无锁编程数据结构。

到此,关于“C++中为什么不要使用无锁编程方式”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!

推荐阅读:
  1. C++中的传参方式
  2. C++中各种初始化方式示例详解

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

c++

上一篇:C++中为什么不要返回指向局部对象的指针或引用

下一篇:Web开发中的调色板工具有哪些

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》