"Andrew Pinski" <[EMAIL PROTECTED]> writes: > And it is not a new problem, if conversion has > been with GCC since the 2.95 days so I don't understand why it is only > being brought up now (except threading programming is becoming more > popular). And really I still say these are thread safe, just not the > way you think of them being thread safe.
Misunderstanding of what code is thread safe is common, because the abstract memory model in the language standard does not conform to people's näive assumptions about memory accesses. People assume that memory will be accessed more or less as described in the code, but of course the standard has no such requirement. The standard permits just about anything, including, e.g., promoting globals to register variables. The standard gives exactly one out, which is that volatile requires the compiler to implement the näive memory model. Unfortunately that is not what most people want either. Until the C++0x memory model is implemented, people writing code that has to be thread safe need to use memory barriers around reads and writes to shared data. There is no standard approved way to implement a memory barrier, but acquiring or releasing a mutex should do it. And even memory barriers do not suffice if you are accessing bitfields, or, in general, fields in a struct which are smaller than int. This can break if you want to use different mutexes to protect different fields in the struct. The compiler may modify such fields using a read-partial modify-write cycle which will silently change adjacent fields in the struct. There are lots of problems with multi-threaded C/C++ code and few good solutions. It would be nice to figure out how gcc could improve matters. The answer is not going to be to disable certain optimizations. But perhaps we should implement the draft C++0x memory model for both C and C++. Ian