I have investigated ABA problem in Concurrency in practice book, in Wikipedia and I have read following post
As I understand the root cause of ABA problem that in algoritm we check that state same as was before but algorithm implies that state was untouched.
Example with a stack data structure:
to add element to stack we use following algorithm:
create new stack node(save to `newNode` variable)
while(true) {
oldHead = stack.get();
newNode.next = oldHead; // point_1
if(stack.compareAndSet(oldhead, newNode)) { // atomically replace head if now head same as was in start of iteration
break;
}
}
Steps which lead to the ABA problem:
Initial state
a->b->c // a-head, c- tail.
Thread_1 tries to add value
d
to the stack and OS suspend the thread beforecompareAndSet
operation(point_1)Thread_2 then execute pop (Thread_1 still suspended)
b->c // b-head, c- tail.
Thread_3 then execute pop (Thread_1 still suspended)
c // c-head, c- tail.
Thread_4 then executes push
a
(Thread_1 still suspended)a->c // a-head, c- tail.
Thread_1 wakes up and and cas operation executes successfully although it can be undesirable in some cases.
Although this answer is accepted I don't understand why automatic garbage collection eliminates the problem.
Although I am not expert in C I understand that in C you cannot allocate one memory range for two different object.
Can you clarify it more clearly?