3 ms·
The code is simply incorrect. Use locking (pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock) if you need to do something like that. C and C++ hav
by nsajko 7y ago
The code is simply incorrect. Use locking (pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock) if you need to do something like that. C and C++ have the same memory model, but this would be wrong in any language.
- gwd 7y agoOh, right! All Linux has to do then is link pthread into the kernel and all their problems will magically go away.</snark> The original purpose of C was to write operating systems; at some point that was basically discarded, and it is now incredibly difficult to write an operating system safely in C anymore. It's like juggling lightsabers.
- nsajko 7y agoIf somebody does not get basic concurrency, it seems appropriate to point them to POSIX Threads' locks, they are obviously not ready to start hacking on the kernel: https://www.kernel.org/doc/htmldocs/kernel-locking/locks.html https://www.kernel.org/doc/htmldocs/kernel-locking/locks.htm...
- CodeMage 7y agoYes, but it's much more helpful -- and less abrasive -- to do so after answering their actual question.
- jcranmer 7y agoThe Linux kernel has chosen to adopt a memory model and a threading model. This was done even before C++11/C11 defined a memory model, and the two systems are quite similar and can mostly be built on top of one another (READ_ONCE/WRITE_ONCE is sort of the odd man out, but it works if you assume the semantics of volatile are "do not eliminate or rematerialize this load/store," which is a correct model if you look at compiler implementations). In practice, the memory model of real hardware systems do a much more thorough job of screwing you up than compiler optimizations, so any practical operating system already needs to build a memory model that can cope with hardware reordering. The only interaction you need with the compiler is a few hooks to stop optimizations, which are quite easy to build in (an empty volatile asm that clobbers memory will prevent reordering of memory operations, for example), and newer language standards actually give you specific mechanisms that give you the building blocks without the need to resort to inline asm tricks.