mercredi 1 juin 2016

new_node->next update in compare_exchange_weak

http://ift.tt/1O0vRJX

template<typename T>
class stack
{
    std::atomic<node<T>*> head;
 public:
    void push(const T& data)
    {
        node<T>* new_node = new node<T>(data);

      // put the current value of head into new_node->next
      new_node->next = head.load(std::memory_order_relaxed);

      // now make new_node the new head, but if the head
      // is no longer what's stored in new_node->next
      // (some other thread must have inserted a node just now)
      // then put that new head into new_node->next and try again
      while(!head.compare_exchange_weak(new_node->next, new_node,
                                        std::memory_order_release,
                                        std::memory_order_relaxed))
          ; // the body of the loop is empty

Question> I have difficulties to understand how the new_node->next will be automatically pointing to the new head if there is another thread that has inserted a new node. For more generic cases, where the variable head is not necessary a single linked list, how the compare_exchange_weak works in that case?

Thank you

Aucun commentaire:

Enregistrer un commentaire