sobota, 15 marca 2014

When to use volatile in c++ ?


TL;DR:Use only for reading hardware registers, never use for shared data between threads. For shared data use locks.


Chandon:
Volatile is intended for poking hardware registers. Using it for threading is almost certainly going to go horribly wrong, because it provides a nearly-but-not-quite useful set of guarantees for that application.
It could do all kinds of things, including fun stuff like requiring that every read or write skip all levels of cache and go out to physical RAM. Needless to say, that's significantly slower than a lock would be.

References:
http://www.reddit.com/r/programming/comments/208x6o/can_i_skip_the_lock_when_reading_an_integer/cg1776e