Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread safe local variable

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?)

like image 266
Gam Avatar asked Mar 28 '16 09:03

Gam


2 Answers

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.

like image 71
Nawaz Avatar answered Nov 19 '22 01:11

Nawaz


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.

like image 2
David Schwartz Avatar answered Nov 19 '22 01:11

David Schwartz