I think that the implementation has other problem:Let us suppose that two threads are working on a non-empty lock free stack:
- thread A calls push() to add a new node, after the line of code new_node.ptr->next=head.load(std::memory_order_relaxed); has beenexecuted, thread A goes to sleep;
- thread B calls pop() to remove an old node, after the line of codeincrease_head_count(old_head); has been executed, thread B goes intosleep;
- thread A continues to run, and finds that the external reference count of the head node is not 1, but the information will be ignored, and the new node will be added to the stack as the new head;
- thread B continues to run, and head.compare_exchange_strong() will be failed, and ptr->internal_count.fetch_add(-1, std::memory_order_relaxed) will be executed, it causes that the external reference count of the old head pointer is still 2, but the internal reference count is -1.
- so the lock free stack is broken!
Who can help to check whether it is a real problem?