0

I have recently started exploring C++11 threads. I am using eclipse for sample programs. Output in the Eclipse console is confusing me.

When I make the detached thread wait for a second, I don't see the output from detached thread in the console.

If I don't make detached thread wait, console output seems proper.

#include<iostream>
#include<thread>
#include<chrono>

using std::cout;
using std::endl;
using std::thread;

void hello(){
    std::this_thread::sleep_for(std::chrono::seconds(5));
    cout << "hello from hello!" << endl;
}
int main(){

    thread(hello).detach();

    cout << "hello from main" << endl;

    return 0;
}

Console output: hello from main

If hello method is as followed, output seems okay.

void hello(){
    //std::this_thread::sleep_for(std::chrono::seconds(1));
    cout << "\nhello from method!" << endl;
}

Console output: hello from main hello from method!

Could someone please help me understand what is happening here?

DBR404
  • 1
  • you need to wait in main thread. – apple apple Mar 01 '18 at 06:54
  • 1
    Possible duplicate of [What happens to a detached thread when main() exits?](https://stackoverflow.com/questions/19744250/what-happens-to-a-detached-thread-when-main-exits) – apple apple Mar 01 '18 at 06:54
  • Is this specifically when running in eclipse, or does it happen if you run your program from the console? I suspect eclipse's stream handling is just slightly leaky in the case that a thread prints just as the program exits. – Gem Taylor Mar 01 '18 at 11:03
  • Same thing when run from console too! (tried from cygwin terminal on windows) – DBR404 Mar 01 '18 at 12:47
  • @appleapple thanks! that helped. Would the behavior be same on visual studio? – DBR404 Mar 01 '18 at 14:07
  • @BharathReddy If you wait, it should be the same, but I'm not sure if you don't. – apple apple Mar 02 '18 at 02:05

0 Answers0