fork download
  1. #include <cstdlib>
  2. #include <chrono>
  3. #include <iostream>
  4. #include <thread>
  5.  
  6. int p = 0;
  7. int *q = nullptr;
  8.  
  9. void g()
  10. {
  11. using namespace std::chrono_literals;
  12.  
  13. std::cout << "g()" << std::endl;
  14.  
  15. std::cout << "g(): p = 1" << std::endl;
  16. p = 1;
  17.  
  18. std::this_thread::sleep_for(1s);
  19.  
  20.  
  21. if (q != nullptr) {
  22. std::cout << "g(): *q = 1" << std::endl;
  23. *q = 1;
  24. } else {
  25. std::cout << "g(): q == nullptr" << std::endl;
  26. }
  27. }
  28.  
  29. void f()
  30. {
  31. using namespace std::chrono_literals;
  32.  
  33. std::cout << "f()" << std::endl;
  34.  
  35. if (p == 0) {
  36. std::cout << "f(): first loop start" << std::endl;
  37. while (p == 0) { } // Потенциально конечный
  38. std::cout << "f(): first loop end" << std::endl;
  39. }
  40.  
  41. int i = 0;
  42. q = &i;
  43. std::cout << "f(): second loop start" << std::endl;
  44. while (i == 0) { } // Потенциально конечный, хотя в условии только автоматическая пельменная
  45. std::cout << "f(): second loop end" << std::endl;
  46. }
  47.  
  48. int main()
  49. {
  50. using namespace std::chrono_literals;
  51.  
  52. std::cout << "f() thread start" << std::endl;
  53. auto thr1 = std::thread(f);
  54. thr1.detach();
  55. std::this_thread::sleep_for(1s);
  56.  
  57. std::cout << "g() thread start" << std::endl;
  58. auto thr2 = std::thread(g);
  59. thr2.detach();
  60. std::this_thread::sleep_for(2s);
  61.  
  62. std::cout << "Done" << std::endl;
  63.  
  64. std::_Exit(EXIT_SUCCESS);
  65. }
  66.  
Success #stdin #stdout 3s 4192KB
stdin
Standard input is empty
stdout
f() thread start
f()
f(): first loop start
g() thread start
g()
g(): p = 1
g(): q == nullptr
Done