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

链接:
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;
没找到下文,只能参考内核的kfifo了

猜你喜欢

转载自blog.csdn.net/alpha_007/article/details/115064906