c++ - Could optimization break thread safety? -
class foo{ public: void fetch(void) { int temp=-1; someslowfunction(&temp); bar=temp; } int getbar(void) { return bar; } void someslowfunction(int *ptr) { usleep(10000); *ptr=0; } private: int bar; };
i'm new atomic operations may concepts wrong.
considering above code, assuming loading , storing int
type atomic[note 1], getbar()
bar
before or after fetch()
.
however, if compiler smart enough, optimize away temp
, change to:
void foo::fetch(void) { bar=-1; someslowfunction(&bar); }
then in case getbar()
-1
or other intermediate state inside someslowfunction()
under timing conditions.
is risk possible? standard prevent such optimizations?
note 1: http://preshing.com/20130618/atomic-vs-non-atomic-operations/
the language standards have nothing atomicity in case. maybe integer assignment atomic, maybe isn’t. since non-atomic operations don’t make guarantees, plain integer assignment in c non-atomic definition.
in practice, know more our target platforms that. example, it’s common knowledge on modern x86, x64, itanium, sparc, arm , powerpc processors, plain 32-bit integer assignment atomic long target variable naturally aligned. can verify consulting processor manual and/or compiler documentation. in games industry, can tell lot of 32-bit integer assignments rely on particular guarantee.
i'm targeting arm cortex-a8 here, consider safe assumption.
compiler optimization can not break thread safety!
you might experience issues optimizations in code appeared thread safe worked because of pure luck.
if access data multiple threads, must either
- protect appropriate sections using
std::mutex
or like. - or, use
std::atomic
.
if not, compiler might optimizations next impossible expect.
i recommend watching cppcon 2014: herb sutter "lock-free programming (or, juggling razor blades), part i" , part ii
Comments
Post a Comment