std::atomic
has some operators like: +, -, ++, -- (post and pre) and guarantee that they are thread safe, but is comparison operations thread safe? I mean following:
std::atomic<int> a = 10;
int i = 20;
void func() {
a++; // atomic and thread safe
if (a > i) // is it thread safe?
}
This is thread-safe only if:
i
never changes (you really should make it const
)a++
changes the value to be larger than i
, that a successive atomic load will satisfy a > i
. Two separate atomic instructions are not atomic.Note the last point here. You are free to compare a > i
. This will atomically acquire the current value of a
and then use that value to compare against i
. However the actual value of a
might change immediately afterwards. As long as your branch doesn't rely on that not happening, this is fine.
if( a > i )
{
// a is not guaranteed to be greater than i at this point.
}
I'm not quite sure how you want your logic to work, but it's possible you might have meant this:
if( ++a > i )
{
// a is still not guaranteed to be greater than i at this point,
// but AT THE TIME OF INCREMENTING it did exceed i.
}
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