fork(1) download
  1. #include <thread>
  2. #include <iostream>
  3. #include <vector>
  4. #include <mutex>
  5. #include <list>
  6.  
  7. class Hello
  8. {
  9. int i_;
  10. static std::mutex mu_;
  11. public:
  12. Hello()
  13. {
  14. std::lock_guard<std::mutex> lock(mu_);
  15. i_ = 0;
  16. }
  17.  
  18. ~Hello()
  19. {
  20. }
  21.  
  22. void say_hello()
  23. {
  24. std::lock_guard<std::mutex> lock(mu_);
  25. std::cout << "say_hello from thread " << ++i_ << " " << this << " " << std::this_thread::get_id() << std::endl;
  26. }
  27. };
  28.  
  29. std::mutex Hello::mu_;
  30.  
  31. void hellos_in_threads_stack()
  32. {
  33. std::vector<std::thread> threads;
  34. for (int i = 0; i < 4; ++i)
  35. {
  36. threads.emplace_back([]() {
  37. Hello h;
  38. h.say_hello();
  39. });
  40. }
  41.  
  42. for (auto& thread : threads) {
  43. thread.join();
  44. }
  45. }
  46.  
  47.  
  48. void hellos_in_list()
  49. {
  50. std::vector<std::thread> threads;
  51. std::list<Hello> hellos;
  52. for (int i = 0; i < 4; ++i)
  53. {
  54. hellos.emplace_back();
  55. threads.emplace_back(&Hello::say_hello, &hellos.back());
  56. }
  57.  
  58. for (auto& thread : threads) {
  59. thread.join();
  60. }
  61. }
  62.  
  63. int main()
  64. {
  65. hellos_in_threads_stack();
  66. hellos_in_list();
  67. }
Success #stdin #stdout 0s 4560KB
stdin
Standard input is empty
stdout
say_hello from thread 1 0x2b091e654ed0 47318164657920
say_hello from thread 1 0x2b091e453ed0 47318162556672
say_hello from thread 1 0x2b091e252ed0 47318160455424
say_hello from thread 1 0x2b091e051ed0 47318158354176
say_hello from thread 1 0x5641fa338da0 47318158354176
say_hello from thread 1 0x5641fa338dc0 47318160455424
say_hello from thread 1 0x5641fa338c30 47318162556672
say_hello from thread 1 0x5641fa338c50 47318164657920