What am I doing wrong?

#include <thread> #include <iostream> void func() { for (int i = 0; i < 10000000; ++i) std::cout << i << "\n"; } 

one)

 int main() { std::thread t1(func); std::thread t2(t1); t1.join(); t2.join(); return 0; } 

2)

 int main() { std::thread t(func); t.detach(); return 0; } 

In the second, nothing is displayed.
In the first shouts at

  std::thread t2(t1); 

    1 answer 1

     int main() { std::thread t1(func); std::thread t2(t1); t1.join(); t2.join(); return 0; } 

    Streams are not copied. Create a new thread with the same function -

      std::thread t2(func); 

    Here

     int main() { std::thread t(func); t.detach(); return 0; } 

    You created a thread, allowed it to run, and immediately ended the program. The stream is a part of the program, it also immediately turns out to be killed, before it even had time to start, not only to get something out ...

    Check out https://ideone.com/ckpRLm and https://ideone.com/UNwYlJ

    • OK. thank. std :: this_thread :: sleep_for (std :: chrono :: seconds (2)); - and how can I write this in another way? - Oksana Volinets
    • This is just a delay of 2 seconds. You can use sleep , but why? times your compiler C ++ 11 supports ... - Harry