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

这篇文章主要介绍“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++中为什么不要使用无锁编程方式”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!