Stop an infinite loop in different threads

In my application, I use several threads to perform a multitask task that is designed to work throughout the duration of the application. What I'm trying to achieve is a good and clean approach to kill the loop in the second thread just before exiting the application, so I can clear after the loop and then close everything.

So far I have come up with this approach, but honestly, I am not a 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;
}
+4
source share
2 answers

- undefined. , .

, std::atomic_bool. - foo " ".

void foo(std::atomic_bool& cancellation_token)
{
    while(!cancellationToken)
    {
        //do something
    }
    clean_after();
}
+3

:

std::atomic<bool> stop_flag;
+9

Source: https://habr.com/ru/post/1665777/


All Articles