Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop infinite loop in different thread

In my application I am using multiple threads for some time consuming task, that is intended to run for the whole duration f the application. What I am trying to achieve is some nice and clean approach to kill the loop in second thread just before exiting app, so I can clean after loop and then close everything.

So far I've come up with this approach, but to be honest I am not huge fan of it:

#include <iostream>
#include <thread>

bool stop_flag;

void foo()
{
    while(!stop_flag)
    {
        //do something
    }
    clean_after();
}

int main()
{
    stop_flag = false;
    std::thread whileThread(foo);

    // app lifetime

    stop_flag = true;   
    whileThread.join();
    return 0;
}
like image 737
sebap123 Avatar asked Jan 04 '17 18:01

sebap123


2 Answers

With just a slight change, your code will be fine:

std::atomic<bool> stop_flag;
like image 168
Pete Becker Avatar answered Sep 21 '22 11:09

Pete Becker


reading and writing to the same un-synchronized variable from multiple thread is anyway undefined behavior. Fan or not, the compiler may just optimize the check away and the loop may never start or never end.

as answered before, you can use std::atomic_bool. I'm not a fan of doing it globally - pass it to foo as its "cancellation token".

void foo(std::atomic_bool& cancellation_token)
{
    while(!cancellationToken)
    {
        //do something
    }
    clean_after();
}
like image 39
David Haim Avatar answered Sep 19 '22 11:09

David Haim