fork download
  1. #include <thread>
  2. #include <atomic>
  3. #include <cassert>
  4. #include <vector>
  5.  
  6. std::vector<int> data;
  7. std::atomic<int> flag = ATOMIC_VAR_INIT(0);
  8.  
  9. void thread_1()
  10. {
  11. data.push_back(42);
  12. flag.store(1, std::memory_order_release);
  13. }
  14.  
  15. void thread_2()
  16. {
  17. int expected=1;
  18. while (!flag.compare_exchange_strong(expected, 2, std::memory_order_acq_rel)) {
  19. expected = 1;
  20. }
  21. }
  22.  
  23. void thread_3()
  24. {
  25. while (flag.load(std::memory_order_acquire) < 2)
  26. ;
  27. assert(data.at(0) == 42); // will never fire
  28. }
  29.  
  30. int main()
  31. {
  32. std::thread a(thread_1);
  33. std::thread b(thread_2);
  34. std::thread c(thread_3);
  35. a.join(); b.join(); c.join();
  36. }
Runtime error #stdin #stdout #stderr 0s 3472KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted