6

In the new C++11 standard, many atomic operations are defined in "strong/weak" pairs:

template< class T >
bool atomic_compare_exchange_weak( std::atomic<T>* obj, 
                                   T* expected, T desired );
template< class T >
bool atomic_compare_exchange_weak( volatile std::atomic<T>* obj, 
                                   T* expected, T desired );

I understand that the weak one may be faster, but may fail occasionally, so one needs to put it into a while loop like below (taken from cppreference):

void append(list* s, node* n)
{
    node* head;
    do {
        head = s->head;
        n->next = head;
    } while(! std::atomic_compare_exchange_weak(s->head, head, n));
}

But

  1. What exactly do the weak operations do? Why do they sometimes fail, and why are they faster? (I would love some hardcore microprocessor architecture details.)

  2. When is the weak form preferable, and when is the strong one recommended?

Sam
  • 19,708
  • 4
  • 59
  • 82
  • 2
    I wonder if this old question is useful http://stackoverflow.com/q/4944771/46642 – R. Martinho Fernandes Mar 12 '13 at 16:00
  • @R.MartinhoFernandes, it would be useful if the answer was accurate ;-) – Jonathan Wakely Mar 12 '13 at 16:13
  • I am trying to understand the rules of this site, so if it is a stupid question, please bear with me. Why is this tagged algorithm? – Knoothe Mar 12 '13 at 16:15
  • @JonathanWakely ah, I wouldn't know, which is why I only offered it tentatively (no close vote) and am eagerly awaiting for a better one here ;) – R. Martinho Fernandes Mar 12 '13 at 16:15
  • @Knoothe because the original poster did and no one disagreed so far. I hadn't noticed it, and I don't think it fits. – R. Martinho Fernandes Mar 12 '13 at 16:16
  • 5
    @R.MartinhoFernandes, I do agree it's the same quetion, so I've added my own answer to the linked question, with what I understand to be the reason – Jonathan Wakely Mar 12 '13 at 16:24
  • @Knoothe, algorithm tag was stupid. The other question's references seem to cover what I wanted, just I would have to read them all to be sure :) – Sam Mar 12 '13 at 16:48
  • 1
    @JonathanWakely The answer posted on the other question is what I wanted. Thanks! (I won't accept it, though, because I cannot :) ) – Sam Mar 12 '13 at 16:52

0 Answers0