c++ - Using volatile for a shared variable between WinAPI threads -
the c++ compiler not know threads, c++ compiler sees "thread" function.
now have 2 threads/functions, , have 1 global variable.
if accessing global variable in these 2 threads/functions, c++ compiler optimize variable access code in these 2 threads , copy global variable register , start manipulating register , not memory location. since each thread have unique set of registers, if these 2 threads running simultaneously, not accessing global variable in memory, rather each thread manipulating own register!
so if make global variable volatile
, tell c++ compiler not optimize access code variable, , access memory location directly.
is correct?
yes. no. maybe.
in modern, standard, cross platform c++ volatile
neither necessary nor sufficient achieve doing. because tell compiler not optimize out read not tell cpu/memory read/write shouldn't re-ordered. , standard says reading somewhere whilst may writing undefined behavoir. may away on x86/x64 due unreasonably strong memory models shouldn't take risk. volatile
drivers , os's talk hardware.
you should use modern way of doing using std::atomic<...>
. can safetly read , write simultaneously std::atomic
, reads/writes not optimized away*. right choice.
however... if writing exclusively windows , using flavor of visual studio compiler gives additional guarantees when using volatile
work in case right compiler options. vs increases strength of guarantee volatile
similar c# & java uses volatile for. means in case work. on latest version of vs can control behavoir through /volatile compiler option. however, not recommend doing unless necessary. use standard std::atomic's unless dont have choice.
note c++/java , vs's extension volatile weaker using std::atomic
. std::atomic
's guarantee sequential consistancy neither java nor c# means dekkers algorithm can used std::atomic.
*std::atomic
's can optimised out if couldn't possibly notice under as-if rule. reason they're better volatile
break optimizations must done if unnecessary impossible compiler reason about.
Comments
Post a Comment