In C++11 there is the std::atomic_flag that is useful for thread loops:
static std::atomic_flag s_done(ATOMIC_FLAG_INIT);
void ThreadMain() {
while (s_done.test_and_set()) { // returns current value of s_done and sets to true
// do some stuff in a thread
}
}
// Later:
s_done.clear(); // Sets s_done to false so the thread loop will drop out
The ATOMIC_FLAG_INIT sets the flag to false which means that the thread never gets in the loop. A (bad) solution is possibly to do this:
void ThreadMain() {
// Sets the flag to true but erases a possible false
// which is bad as we may get into a deadlock
s_done.test_and_set();
while (s_done.test_and_set()) {
// do some stuff in a thread
}
}
The default constructor for std::atomic_flag specifies that the flag will be in an unspecified state.
Can I initialize the atomic_flag to true? Is this the correct use of the atomic_flag?
You could always call test_and_set before starting the thread.
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