void HelloWorld()
{
static std::atomic<short> static_counter = 0;
short val = ++static_counter; // or val = static_counter++;
}
If this function is called from two threads,
Can the local variable val be 1 in both threads? or (0 if static_counter++ is used?)
Can the local variable val be 1 in both threads?
No. ++static_counter is equivalent to:
fetch_add(1)+1
which cannot return same value for two (or more) threads because fetch_add is executed atomically.
No. The only way val could have the same value in both threads is if the two atomic operations overlapped. By definition, atomic operations cannot overlap.
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