Question

I am wondering why a function doWork() is called without the upper code being exectued. The code is the following:

void doWork()
{
std::cout<<"Hello World>";
sleep(1);
doWork();
}

....

void foo()
{
std:cout<<"This is text is never seen in the console but doWork timer callback works";
std::thread thread([&]{doWork();});
}

Why is std:cout not working but std::thread is being executed?

Thanks

Was it helpful?

Solution

  1. You don't flush the buffer. Try adding << std::flush or << std::endl at the end.

  2. You need to wait for execution in the thread to finish before the object thread is destructed.

    thread.join(); // Wait for thread to finish.
    
  3. You don't need to capture everything as references in the lambda ([&]). You don't seem to use any of those captures.

  4. If you're using the portable C++11 std::thread library, don't use Linux-specific sleep function. Instead use std::this_thread::sleep_for, e.g:

    void doWork() {             // (1. Flush buffer here too)
        std::cout << "Hello World>" << std::flush;
                                // 4. Use portable sleep.
        std::this_thread::sleep_for(std::chrono::seconds(1));
        doWork();
    }
    
    // ....
    
    void foo() {
                                // 1. Flush buffer.
        std::cout << "This text is seen in the console" << std::endl;
        std::thread thread([] { // 3. No need to capture everything by reference
            doWork();
        });
        thread.join();          // 2. Wait for thread to finish.
    }
    

OTHER TIPS

cout is buffered, if the buffer is not flushed it will not immediately print.

You can use:

std::cout << "Text" << std::endl;

Or:

std::cout << "Text\n" << std::flush;

To flush the buffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top