fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <mutex>
  4. #include <atomic>
  5. #include <assert.h>
  6. using namespace std;
  7.  
  8. std::atomic<bool> x;
  9. atomic<bool> y;
  10. atomic<int> z;
  11.  
  12. void write_x_then_y(){
  13. x.store(true, memory_order_relaxed);
  14. y.store(true, memory_order_relaxed);
  15. }
  16.  
  17. void read_y_then_x(){
  18. while(!y.load(memory_order_relaxed));
  19. if (x.load(memory_order_relaxed)){
  20. ++z;
  21. }
  22. }
  23.  
  24. int main() {
  25. x = false;
  26. y = false;
  27. z = 0;
  28. std::thread a(write_x_then_y);
  29. std::thread b(read_y_then_x);
  30. a.join();
  31. b.join();
  32. assert(z.load() != 0);
  33. return 0;
  34. }
  35.  
  36. void write_x_read_x_write_y(){
  37. x.store(true, memory_order_relaxed);
  38. int z = x.load();
  39. y.store(true, memory_order_relaxed);
  40. }
Success #stdin #stdout 0s 7564KB
stdin
Standard input is empty
stdout
Standard output is empty