Disabling C ++ 11 thread

This setting

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();
}

      

Doesn't give me exit until I hit enter (getchar returns and ends with the program, but I can see the result for a short while). However, when using the comment line from foo, the output is displayed directly. (Even after foo returns.) I am using VS11 beta. What behavior is required here by the standard?

+3


source to share


3 answers


"\n"

does not clear the output buffer. You need to use std::endl

instead that flushes the buffer.



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

      

+4


source


You can try using std::flush

cout to manually flush the buffer



+3


source


I think this is because you are using std :: cout, whick is buffered. Try it with std :: cerr.

-five


source







All Articles