Quantcast
Channel: Can a write to std::atomic go unseen by other threads while using std::atomic::compare_exchange_strong? - Stack Overflow
Viewing all articles
Browse latest Browse all 2

Can a write to std::atomic go unseen by other threads while using std::atomic::compare_exchange_strong?

$
0
0
std::atomic<int> g_atomic;void thread0(){  int oldVal = 0;  int newVal = 1;  while (g_atomic.compare_exchange_strong(oldVal, newVal, std::memory_order_acq_rel, std::memory_order_acquire))  {    // forever counting from 0 to 100 until unexpected value appears    oldVal = newVal;    newVal = (oldVal + 1) % 100;  };}void thread1(){  // set unexpected value  g_atomic.store(-1, std::memory_order_release);}int main(){  g_atomic.store(0);  std::thread t0(thread0);  std::thread t1(thread1);  t0.join();  t1.join();  return 0;}

Can it happen that the write from thread1 is somehow overwritten in the loop of thread0 before it gets visible in thread0?The program would then run forever. This does not happen in my tests however im interested if there is any guarantee saying this will always be the case.


Viewing all articles
Browse latest Browse all 2

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>