经典永流传2-Lock-Free Code: A False Sense of Security

本文讨论了编写无锁代码时可能遇到的问题,包括内存重排序和编译器/处理器的优化导致的安全隐患。文章指出,为了确保原子性和内存顺序,需要使用如mutex、std::atomic或volatile等工具。作者通过示例解释了如何因为重排序导致的问题,并提醒在更新变量时必须考虑全内存屏障以防止问题发生。此外,还提到了编译器和处理器可能会发明写操作,引入瞬时值,增加了代码的复杂性和潜在错误。
摘要由CSDN通过智能技术生成

链接:
Lock-Free Code: A False Sense of Security

  1. To avoid a race, a lock-free variable must have two key properties that we need to watch for and guarantee: atomicity and ordering

  2. compilers, processors, and caches love to optimize reads and writes, and will helpfully reorder, invent, and remove memory reads and writes unless you prevent it from happening. The right prevention happens implicitly when you use mutex locks or ordered atomic variables (C++0x std::atomic, Java/.NET volatile); you can also do it explicitly, but with considerably more effort, using ordered API calls (e.g., Win32 InterlockedExchange) or memory fences/barriers (e.g., Linux mb). Trying to write lock-free code without using any of these tools can’t possibly work.

  3. This is not enough, cuz list.end() may have side effects, i.e. iTail is assigned before list.end() is complete:

    list.push_back(t);	// A: add the new item
    mb();		// full fence
    iTail = list.end();	// B: publish it
    
  4. Reordering isn’t the only issue. Another problem is that compilers and processors can invent writes, so they could inject a transient value:

    // Problematic compiler/processor transformation

    if (iNext != iTail) {
      iHead = 0xDEADBEEF;
      iHead = iNext;
      t = *iHead;
    

没明白啥意思: iHead = 0xDEADBEEF;
下文链接:
Writing Lock-Free Code: A Corrected Queue

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值