Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a comparison operation thread safe for std::atomic variables?

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? 
}
like image 947
rdo Avatar asked Feb 07 '23 23:02

rdo


1 Answers

This is thread-safe only if:

  • i never changes (you really should make it const)
  • You don't expect that if 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.
  • You don't require the branching code to be 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.
}
like image 115
paddy Avatar answered Feb 10 '23 13:02

paddy