I'm reading C++ Concurrency in Action by Anthony Williams, and don't understand its push
implementation of the lock_free_stack
class.
Why on earth the atomic load
is not in the while loop ? The reason he gave is:
You therefore don’t have to reload head each time through the loop, because the compiler does that for you.
But I don't get the picture. Can someone shed some light on this?
template<typename T>
class lock_free_stack
{
private:
struct node
{
T data;
node* next;
node(T const& data_) :
data(data_)
{}
};
std::atomic<node*> head;
public:
void push(T const& data)
{
node* const new_node=new node(data);
new_node->next=head.load();
while(!head.compare_exchange_weak(new_node->next,new_node));
}
};