ABA problem

转载 2012年03月31日 11:12:48

ABA problem

From Wikipedia, the free encyclopedia
Jump to: navigation, search

In multithreaded computing, the ABA problem occurs during synchronization, when a location is read twice, has the same value for both reads, and "value is the same" is used to indicate "nothing has changed". However, another thread can execute between the two reads and change the value, do other work, then change the value back, thus fooling the first thread in to thinking "nothing has changed" even though the second thread did work that violates that assumption.

The ABA problem occurs when multiple threads (or processes) accessing shared memory interleave. Below is the sequence of events that will result in the ABA problem:

  • Process P_1 reads value A from shared memory,
  • P_1 is preempted, allowing process P_2 to run,
  • P_2 modifies the shared memory value A to value B and back to A before preemption,
  • P_1 begins execution again, sees that the shared memory value has not changed and continues.

Although P_1 can continue executing, it is possible that the behavior will not be correct due to the "hidden" modification in shared memory.

A common case of the ABA problem is encountered when implementing a lock-free data structure. If an item is removed from the list, deleted, and then a new item is allocated and added to the list, it is common for the allocated object to be at the same location as the deleted object due to optimization. A pointer to the new item is thus sometimes equal to a pointer to the old item which is an ABA problem.

[edit] Example

An easy-to-understand example of the ABA problem would be the following real-life scenario:


Charlie is at an airport carrying a briefcase with a large sum of money in it. He is carrying it for his boss, so he does not know the suitcase's combination. An attractive and provocatively-dressed woman (Sharon) approaches him and strikes up a conversation. While Sharon is distracting Charlie, her partner-in-crime (Albert) decides to seize the opportunity to grab the money. He realizes that if Charlie turns around and sees that his briefcase has disappeared, he will sound an alarm; after that, it is not likely that he and Sharon will make it out of the airport without being stopped by security.
Instead, Albert quickly takes Charlie's briefcase and replaces it with an identical briefcase filled with sand to match the weight of the money. Sharon finishes up her conversation with Charlie, he gets up, gets on the plane, and leaves. He is completely unaware that the briefcase now contains only sand. When Charlie's boss finally opens the briefcase, it is likely Charlie will be in a lot of trouble.


In this scenario, the 'A' state is when there is a briefcase next to Charlie, and the 'B' state is when there is nothing next to him. Originally, his briefcase starts in 'A' state. If Charlie had turned around in between the time Albert took his real briefcase and replaced it with the fake, he would've seen his briefcase gone ('B' state) and sounded the alarm. Unfortunately, when he turned back he observed 'A' state and had no choice but to assume that 'B' state never happened.


See the workaround section to find out how Charlie could have prevented this misfortune.


Following are a couple of code examples:

Consider this lock-free stack:

  /* Naive lock-free stack which suffers from ABA problem.*/
  class Stack {
    volatile Obj* top_ptr;
    //
    // Pops the top object and returns a pointer to it.
    //
    Obj* Pop() {
      while(1) {
        Obj* ret_ptr = top_ptr;
        if (!ret_ptr) return 0;
        Obj* next_ptr = ret_ptr->next;
        // If the top node is still ret, then assume no one has changed the stack.
        // (That statement is not always true because of the ABA problem)
        // Atomically replace top with next.
        if (CompareAndSwap(top_ptr, ret_ptr, next_ptr)) {
          return ret_ptr;
        }
        // The stack has changed, start over.
      }
    }
    //
    // Pushes the object specified by obj_ptr to stack.
    //
    void Push(Obj* obj_ptr) {
      while(1) {
        Obj* next_ptr = top_ptr;
        obj_ptr->next = next_ptr;
        // If the top node is still next, then assume no one has changed the stack.
        // (That statement is not always true because of the ABA problem)
        // Atomically replace top with obj.
        if (CompareAndSwap(top_ptr, next_ptr, obj_ptr)) {
          return;
        }
        // The stack has changed, start over.
      }
    }
  };

This code can normally prevent problems from concurrent access, but suffers from ABA problems. Consider the following sequence:

Stack initially contains top → A → B → C

Thread 1 starts running pop:

 ret = A;
 next = B;

Thread 1 gets interrupted just before the CompareAndSwap...

  { // Thread 2 runs pop:
    ret = A;
    next = B;
    CompareAndSwap(A, A, B)  // Success, top = B
    return A;
  } // Now the stack is top → B → C
  { // Thread 2 runs pop again:
    ret = B;
    next = C;
    CompareAndSwap(B, B, C)  // Success, top = C
    return B;
  } // Now the stack is top → C
  delete B;
  { // Thread 2 now pushes A back onto the stack:
    A->next = C;
    CompareAndSwap(C, C, A)  // Success, top = A
  }

Now the stack is top → A → C

When Thread 1 resumes:

 CompareAndSwap(A, A, B)

This instruction succeeds because it finds top == ret (both are A), so it sets top to next (which is B). As B has been deleted the program will access freed memory when it tries to look the first element on the stack. Accessing freed memory is undefined, in the sense there are numerous difficult to debug ways your program will crash, so a program will soon crash in a difficult to debug manner.

[edit] Workarounds

Going back to the previous example of Charlie and his briefcase, what could Charlie have done differently?

There are a number of ways that Charlie could have prevented this from happening, even though he can't open the briefcase. For one, he could've chained the real briefcase to the seat. That way, Albert would have to cut the chain to steal the briefcase, and Charlie would notice the cut chain and sound the alarm. This is what the LL/SC instruction on some processors attempts to do. Another solution would be for Charlie to write down the serial number of his real briefcase, and check it after every time he looks away from it. This is how Double-Word Compare-And-Swap Tagging works. Automatic Garbage Collection, along with other techniques like Hazard Pointers, deal with this problem by ensuring that there is no other briefcase in the world that looks like Charlie's briefcase. When Charlie, his boss, and whoever else cares about the briefcase don't need it anymore, it is destroyed. Then, and only then, is another briefcase that looks like his allowed to be created.

Below are examples of code mechanisms that implement the ideas above.

A common workaround is to add extra "tag" bits to the quantity being considered. For example, an algorithm using compare and swap on a pointer might use the low bits of the address to indicate how many times the pointer has been successfully modified. Because of this, the next compare-and-swap will fail, even if the addresses are the same, because the tag bits will not match. This does not completely solve the problem, as the tag bits will eventually wrap around, but helps to avoid it. Some architectures provide a double-word compare and swap, which allows for a larger tag. This is sometimes called ABA' since the second A is made slightly different from the first.

A correct but expensive approach is to use intermediate nodes that are not data elements and thus assure invariants as elements are inserted and removed [Valois].

Another approach is to defer reclamation of removed data elements. One way to defer reclamation is to run the algorithm in an environment featuring an automatic garbage collector. Another way to defer reclamation is to use one or more hazard pointers, which are pointers to locations that otherwise cannot appear in the list. Each hazard pointer represents an intermediate state of an in-progress change; the presence of the pointer assures further synchronization [Doug Lea]. Yet another way to defer reclamation is to use read-copy update (RCU), which involves enclosing the update in an RCU read-side critical section and then waiting for an RCU grace period before freeing any removed data elements. Using RCU in this way guarantees that any data element removed cannot reappear until all currently executing operations have completed.

Some architectures provide "larger" atomic operations such that, as example, both forward and backward links in a doubly linked list can be updated atomically.

Some architectures provide a load linked, store conditional instruction in which the store is performed only when there are no other stores of the indicated location. This effectively separates the notion of "storage contains value" from "storage has been changed". Examples include DEC Alpha, MIPS, PowerPC and ARM (v6 and later). However no practical implementations of load linked will directly solve the ABA problem. [Michael]

[edit] References

  1. Damian Dechev, Peter Pirkelbauer, and Bjarne Stroustrup. Lock-free Dynamically Resizable Arrays
  2. Maged M. Michael. ABA Prevention Using Single-Word Instructions (LL/SC)

The ABA Problem

ABA problem 在多线程环境下,在同步的过程中可能会发生ABA问题。如果一个线程对同一片内存区域进行两次读取,发现两次读取的内容相同,那么它会认为在这个两次读取过程中系统状态没有发生改变,可...
  • u011018348
  • u011018348
  • 2018年01月09日 14:28
  • 21

2017浙江理工校赛 A、D、I 待补完

可做题很多,这几天补完! Problem A: 回文 Time Limit: 1 Sec  Memory Limit: 128 MB Submit: 1672  Solved: 517 De...
  • kyoma
  • kyoma
  • 2017年03月22日 21:04
  • 322

ABA问题及其java解决方案

1. ABA问题入门级探讨 2. 用AtomicStampedReference解决ABA问题 第二篇文章说了一下aba的坏处,比较经典...
  • randyjiawenjie
  • randyjiawenjie
  • 2013年12月30日 19:39
  • 3945

CAS和ABA问题

CASCAS全称是CompareAndSwap,是一条CPU的原子指令,其作用是让CPU经过比较后原子地更新某个位置的值,CAS是靠硬件实现的,JVM只是封装了汇编调用,那些AtomicInteger...
  • peerless_hero
  • peerless_hero
  • 2017年02月17日 19:10
  • 461

传说中的并发编程ABA问题

什么是ABA问题 ABA并不是一个缩写,更像是一个形象的描述。ABA问题出现在多线程或多进程计算环境中。 首先描述ABA。假设两个线程T1和T2访问同一个变量V,当T1访问变量V时,读取到...
  • u012813201
  • u012813201
  • 2017年06月02日 10:17
  • 564

ABA问题及避免

本文使用一个案例介绍ABA是如何产生的,并且介绍如何去避免发生这种异常情况...
  • li954644351
  • li954644351
  • 2016年01月13日 16:58
  • 1084

多线程(十二)CAS 和ABA问题

在JDK 5之前Java语言是靠synchronized关键字保证同步的,这会导致有锁。锁机制存在以下问题:(1)在多线程竞争下,加锁、释放锁会导致比较多的上下文切换和调度延时,引起性能问题。(2)一...
  • u012834750
  • u012834750
  • 2017年04月06日 11:38
  • 970

聊聊高并发(十二)分析java.util.concurrent.atomic.AtomicStampedReference源码来看如何解决CAS的ABA问题

在聊聊高并发(十一)实现几种自旋锁(五)中使用了java.util.concurrent.atomic.AtomicStampedReference原子变量指向工作队列的队尾,为何使用AtomicSt...
  • ITer_ZC
  • ITer_ZC
  • 2014年10月30日 12:29
  • 5241

C++ 无锁队列 ABA <2>

解决ABA问题
  • woshiyuanlei
  • woshiyuanlei
  • 2016年05月11日 19:21
  • 654

AtomicInteger、Unsafe类、ABA问题

AtomicInteger原子类的底层实现
  • WSYW126
  • WSYW126
  • 2017年01月02日 16:19
  • 682
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:ABA problem
举报原因:
原因补充:

(最多只允许输入30个字)