c++ - Is x++; threadsafe? -
if update variable in 1 thread this: receivecounter++;
and thread ever read variable , write value gui.
is safe? or instruction interrupted in middle value in receivecounter wrong when read thread? must right since ++ not atomic, several instructions.
i don't care synchronizing reads , writes, needs incremented , update in gui not have happen directly after each other.
what care value cannot wrong. ++ operation being interrupted in middle read value off.
do need lock variable? not want since update often. solves posting message main thread , copy value queue (which need locked not on every update) guess.
but interested in above problem anyway.
at core read-modify-write operation, not atomic. there processors around have dedicated instruction it. intel/amd cores, common, have inc instruction.
while sounds atomic, since single instruction, still isn't. x86/x64 instruction set doesn't have anymore way execution engine implemented. executes risc-like "micro-ops", inc instruction translated multiple micro-ops. can made atomic lock prefix on instruction. compilers don't emit unless know atomic update desired.
you need explicit it. c++11 std::atomic<> standard addition way. operating system or compiler have intrinsics it, named "interlocked" or "__built_in".
Comments
Post a Comment