fork(2) download
  1. #include<iostream>
  2. #include<thread>
  3. #include<vector>
  4.  
  5. struct Counter {
  6. volatile int value;
  7.  
  8. Counter() : value(0){}
  9.  
  10. void increment(){
  11. value = value + 1000;
  12. }
  13. };
  14.  
  15. int main(){
  16. int n = 10;
  17. while(n--){
  18. Counter counter;
  19.  
  20. std::vector<std::thread> threads;
  21. for(int i = 0; i < 5; ++i){
  22. threads.push_back(std::thread([&counter](){
  23. for(int i = 0; i < 1000000; ++i){
  24. counter.increment();
  25. }
  26. }));
  27. }
  28.  
  29. for(auto& thread : threads){
  30. thread.join();
  31. }
  32.  
  33. std::cout << counter.value << std::endl;
  34. }
  35. return 0;
  36. }
Success #stdin #stdout 0.08s 13712KB
stdin
Standard input is empty
stdout
346608704
-294967296
346807704
65880704
-294967296
225986704
249832704
-294967296
45104704
46084704