Usage of volatile specifier in C/C++/Java

后端 未结 8 1560
旧时难觅i
旧时难觅i 2021-01-03 01:35

While going through many resources on multithreaded programming, reference to volatile specifier usually comes up. It is clear that usage of this keyword is not a reliable w

8条回答
  •  天涯浪人
    2021-01-03 02:32

    The volatile keyword appeared long ago in C, and what it does basically is to "turn off" some compiler optimizations that assume if a variable wasn't changed explicitly, it wasn't changed at all. Its main utility those days was to declare variables that would be changed by interrupt handlers. I, for instance, used it once (late 80's) for a global variable containing the mouse cursor position. The position was changed by an interrupt, and without volatile the main program sometimes wouldn't detect its changes because the compiler optimized away the variable access, thinking it wasn't necessary.

    Today these uses are, in general, obsolete (unless you write low-level OS code) but still there are some rare situations in which volatile is useful (very rare indeed - I, for instance, probably didn't use it for the last 7 years).

    But for multithread programming it's completely unrecommended. The problem is that it won't protect for concurrent access between threads, it will only remove optimizations that would prevent its 'refresh' in the same thread. It wasn't intended for use in multithreaded environments. If you're in Java, use synchronized. If you're in C++, use some sync library, like pthreads or Boost.Threads (or, better yet, use the new C++ 0X thread libraries, if you can).

提交回复
热议问题