sebap123
sebap123

Reputation: 2685

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;
}

Upvotes: 9

Views: 8680

Answers (2)

David Haim
David Haim

Reputation: 26486

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();
}

Upvotes: 8

Pete Becker
Pete Becker

Reputation: 76295

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

std::atomic<bool> stop_flag;

Upvotes: 16

Related Questions