3

I have a question regarding both C++ standard and more generally computer architecture. Imagine following piece of code:

#include <atomic>
#include <thread>

std::atomic<int> a {0};

int main () {

    std::thread t1([&a](){
        int i = 1;
        int ao = a.load();
        while(!a.compare_exchange_weak(ao, i));
    }), t2([&a](){
        int i = 1;
        int ao = a.load();
        while(a.compare_exchange_weak(ao, i));
    });

    t1.join();
    t2.join();
    return 0;
}

I have two questions:

  1. Can this according to standard, in theory lead to thread starvation?
  2. Secondly, can this in practice on x86 architecture lead to starvation? Can I rely on it or no?
bartop
  • 9,971
  • 1
  • 23
  • 54
  • 5
    The operations are ordered.. The first `compare_exchange` will always succeed and end the thread, hence no starvation – LWimsey Aug 25 '18 at 20:17
  • @LWimsey Is it defined in standard of C++ or is it just typical hardware guarantee – bartop Sep 07 '18 at 11:24
  • This is guaranteed by the standard. The operations are sequentially consistent which means that they follow a global order. Ie.all threads observe these operations in the same order. – LWimsey Sep 08 '18 at 20:59
  • See also [Understanding std::atomic::compare_exchange_weak() in C++11](https://stackoverflow.com/questions/25199838/understanding-stdatomiccompare-exchange-weak-in-c11) which has a nice discussion. And see [std::atomic | compare_exchange_weak vs. compare_exchange_strong](https://stackoverflow.com/questions/4944771/stdatomic-compare-exchange-weak-vs-compare-exchange-strong) as well. – Richard Chambers Sep 14 '18 at 19:30

0 Answers0