fork download
  1. #include <iostream>
  2. #include <thread>
  3. #include <vector>
  4.  
  5. int main() {
  6. int shared_counter = 0;
  7.  
  8. std::vector<std::thread> threads;
  9. for (int i = 0; i < 4; ++i) {
  10. threads.emplace_back([&](int id) {
  11. for (int j = 0; j < 1000; ++j) {
  12. ++shared_counter; // Race here: load, increment, store not atomic
  13. }
  14. std::cout << "Thread " << id << " finished.\n";
  15. }, i);
  16. }
  17.  
  18. for (auto& t : threads) t.join();
  19. std::cout << "Final counter: " << shared_counter << " (expect <4000 due to races)\n";
  20. return 0;
  21. }
Success #stdin #stdout 0.01s 5308KB
stdin
Standard input is empty
stdout
Thread 3 finished.
Thread 2 finished.
Thread 1 finished.
Thread 0 finished.
Final counter: 4000 (expect <4000 due to races)