You don't flush the buffer. Try adding
<< std::flush
or<< std::endl
at the end.You need to wait for execution in the thread to finish before the object
thread
is destructed.thread.join(); // Wait for thread to finish.
You don't need to capture everything as references in the lambda (
[&]
). You don't seem to use any of those captures.If you're using the portable C++11
std::thread
library, don't use Linux-specificsleep
function. Instead usestd::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. }
c++: Why is callback executed but function before callback definition not?
-
26-07-2022 - |
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
Solution
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