Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 thread detach

This setup

void run()
{
    while (true)
    {
        std::cout << "Hello, Thread!\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}

void foo()
{
    std::thread t(run);
    t.detach();
    //std::this_thread::sleep_for(std::chrono::seconds(3));
}

int main()
{
    foo();
    getchar();
}

Gives me no output until I press enter (getchar returns and program ends, but I can see the output for a short while). However, when use the out commented line from foo, the output is shown directly. (Even after foo returns.) I'm using the VS11 beta version. Which behavior is required here according to the standard?

like image 670
cooky451 Avatar asked Jan 20 '26 23:01

cooky451


2 Answers

"\n" doesn't flush the output buffer. You need to use std::endl instead which flushes the buffer.

void run()
{
    while (true)
    {
        std::cout << "Hello, Thread!"<<std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}
like image 166
Hossein Avatar answered Jan 23 '26 15:01

Hossein


You could try using std::flush to manually flush the cout buffer

like image 34
jrl Avatar answered Jan 23 '26 16:01

jrl