Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer hangs main thread

I'm trying to implement timer with standard environment Here is a code I have:

bool shutdownDetected = false;

void signal_handler(const int sigid)
{
    shutdownDetected = true;
}

int main(int argc, const char * argv[])
{
    signal(SIGTERM, (sig_t)signal_handler);

    std::async(std::launch::async, [&] () {
        std::this_thread::sleep_for( std::chrono::milliseconds{5000});
        std::cout << "On TIMER!" << std::endl;
    } );

    std::cout << "main function" << std::endl;

    while (!shutdownDetected) {
    }

    return EXIT_SUCCESS;
}

As result I see in output after 5 seconds:

// 5 seconds left
On Timer
main function

but would like to see:

main function
// 5 seconds left
On Timer

Seems that my implementation hangs main thread as well. How to avoid this?

like image 755
Serge Avatar asked Nov 24 '16 20:11

Serge


1 Answers

Your std::async command returns an std::future, which is then immediately destroyed. The problem is that destruction of a future involves 'joining' the thread you created, which means that the destructor is going to wait until the thread has ended itself and code execution in your main thread doesn't advance until that process has completed.

Simple answer is to assign the result of your std::async call to a variable, and possibly call its get() member function in your loop that tests for termination.

auto t = std::async(std::launch::async, [&] () {
    std::this_thread::sleep_for( std::chrono::milliseconds{5000});
    std::cout << "On TIMER!" << std::endl;
} );

std::cout << "main function" << std::endl;

t.get();
like image 164
IanM_Matrix1 Avatar answered Sep 29 '22 10:09

IanM_Matrix1