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;
}
With just a slight change, your code will be fine:
std::atomic<bool> stop_flag;
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With