Potential 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,

Could local val be 1 in both threads? or (0 if using static_counter++ ?)

+5
source share
2 answers

Could local val be 1 in both threads?

No. ++static_counter equivalent to:

  fetch_add(1)+1 

which cannot return the same value for two (or more) threads, because fetch_add is atomically executed.

+2
source

No. The only val method can have the same value in both threads if the two atomic operations overlap. By definition, atomic operations cannot overlap.

+2
source

Source: https://habr.com/ru/post/1245894/


All Articles