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++ ?)
val
1
static_counter++
Could local val be 1 in both threads?
No. ++static_counter equivalent to:
++static_counter
fetch_add(1)+1
which cannot return the same value for two (or more) threads, because fetch_add is atomically executed.
fetch_add
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.
Source: https://habr.com/ru/post/1245894/More articles:"The specified argument was out of range. Parameter name: index" when adding a new element to the ObservableCollection - c #java.util.concurrent.TimeoutException android.view.ThreadedRenderer.finalize () expires in 10 seconds - javaBacking up MySQL using AutoMySQLBackup from a slave to a remote machine - mysqlKendo Multi-Select with flags - kendo-uiWhat are the additional metadata keys available in an ARC welder - google-chrome-arcTomcat8 service could not be started using tomcat8 start service - linuxWhat should I put in the target directory? - javaIs there a supported Java 8 release of SqlJ? - javaImplementing a number with a group in java 8 - javaClass Classobyteconverter Java class Type deprecated - javaAll Articles