1

I have a question about the wait-free multi-producer queue in boost atomic example. I think the 'push' is only lock-free rather than wait-free, because there is a 'compare_exchange_weak loop', then there may be a particular thread in the loop for unpredictable time by some kind of thread scheduling. Besides I think 'pop' is wait-free

Are there mistakes in my understanding?

http://www.boost.org/doc/libs/1_63_0_b1/doc/html/atomic/usage_examples.html#boost_atomic.usage_examples.mp_queue

template<typename T>
class waitfree_queue {
public:
  struct node {
    T data;
    node * next;
  };
  void push(const T &data)
  {
    node * n = new node;
    n->data = data;
    node * stale_head = head_.load(boost::memory_order_relaxed);
    do {
      n->next = stale_head;
    } while (!head_.compare_exchange_weak(stale_head, n, boost::memory_order_release));
  }

  node * pop_all(void)
  {
    T * last = pop_all_reverse(), * first = 0;
    while(last) {
      T * tmp = last;
      last = last->next;
      tmp->next = first;
      first = tmp;
    }
    return first;
  }

  waitfree_queue() : head_(0) {}

  // alternative interface if ordering is of no importance
  node * pop_all_reverse(void)
  {
    return head_.exchange(0, boost::memory_order_consume);
  }
private:
  boost::atomic<node *> head_;
};
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Derek Zhang
  • 101
  • 1
  • 7
  • I found a same question https://stackoverflow.com/questions/40756575/why-multi-producer-queue-in-boost-atomic-usage-is-wait-free, but no one answer it ..... :( – Derek Zhang Apr 11 '19 at 14:30
  • I posted an answer there; this should be closed as a duplicate. (That's fine, interesting question. Reposting like this is basically the only option for old unanswered questions that are actually good and just got overlooked when originally posted.) – Peter Cordes Apr 12 '19 at 00:45

0 Answers0