fork download
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <thread>
  4. #include <atomic>
  5. #include <mutex>
  6.  
  7. using namespace std;
  8.  
  9. mutex out;
  10.  
  11. class Thread
  12. {
  13.  
  14. public:
  15. template<class Fn, class... Args>
  16. Thread(Fn&& Fx, Args&&... Ax):
  17. run(forward<Fn>(Fx), forward<Args>(Ax)...)
  18. ,check([this](){ this->run.join(); this->isDone = true; })
  19. ,isDone(false)
  20. {
  21. }
  22. ~Thread(){ check.join(); }
  23. private:
  24. thread run, check;
  25. public:
  26. atomic<bool> isDone;
  27. };
  28.  
  29. void doit(const char * s, int n)
  30. {
  31. for(int i = 0; i < n; ++i)
  32. {
  33. {
  34. lock_guard<mutex> lock(out);
  35. cout << s << endl;
  36. }
  37. this_thread::sleep_for(10ms);
  38. }
  39. }
  40.  
  41. int main(int argc, char * argv[])
  42. {
  43. try {
  44. Thread t(doit,"Hello",10);
  45. Thread g(doit,"Dolly",20);
  46. for(int i = 0; i < 100; ++i)
  47. {
  48. this_thread::sleep_for(10ms);
  49. {
  50. int count = 0;
  51. lock_guard<mutex> lock(out);
  52.  
  53. if (t.isDone) { cout << "t done\n"; ++count; }
  54. if (g.isDone) { cout << "g done\n"; ++count; }
  55. if (count == 2) break;
  56. }
  57. }
  58. } catch(...) { cerr << "Exception!\n"; }
  59. cout << "Done!\n";
  60. }
Success #stdin #stdout 0.01s 5500KB
stdin
Standard input is empty
stdout
Dolly
Hello
Dolly
Hello
Dolly
Hello
Dolly
Hello
Dolly
Hello
Dolly
Hello
Dolly
Hello
Dolly
Hello
Dolly
Hello
Dolly
Hello
Dolly
t done
Dolly
t done
Dolly
t done
Dolly
t done
Dolly
t done
Dolly
t done
Dolly
t done
Dolly
t done
Dolly
t done
Dolly
t done
t done
g done
Done!