<p>In the C programming language and Pthreads as the threading library; do variables/structures that are shared between threads need to be declared as volatile? Assuming that they might be protected by a lock or not (barriers perhaps).</p>

<p>Does the pthread POSIX standard have any say about this, is this compiler-dependent or neither?</p>

<p>Edit to add: Thanks for the great answers. But what if you're <em>not</em> using locks; what if you're using <a href="http://en.wikipedia.org/wiki/Barrier_(computer_science)" rel="noreferrer">barriers</a> for example? Or code that uses primitives such as <a href="http://en.wikipedia.org/wiki/Compare_and_swap" rel="noreferrer">compare-and-swap</a> to directly and atomically modify a shared variable...</p>

[{'answer_id': 78185, 'author': 'Tom Leys', 'author_id': 11440, 'author_profile': 'https://Stackoverflow.com/users/11440', 'pm_score': 0, 'selected': False, 'text': "<p>Volatile means that we have to go to memory to get or set this value. If you don't set volatile, the compiled code might store the data in a register for a long time. </p>\n\n<p>What this means is that you should mark variables that you share between threads as volatile so that you don't have situations where one thread starts modifying the value but doesn't write its result before a second thread comes along and tries to read the value. </p>\n\n<p>Volatile is a compiler hint that disables certain optimizations. The output assembly of the compiler might have been safe without it but you should always use it for shared values. </p>\n\n<p>This is especially important if you are NOT using the expensive thread sync objects provided by your system - you might for example have a data structure where you can keep it valid with a series of atomic changes. Many stacks that do not allocate memory are examples of such data structures, because you can add a value to the stack then move the end pointer or remove a value from the stack after moving the end pointer. When implementing such a structure, volatile becomes crucial to ensure that your atomic instructions are actually atomic.</p>\n"}, {'answer_id': 78196, 'author': 'Dark Shikari', 'author_id': 11206, 'author_profile': 'https://Stackoverflow.com/users/11206', 'pm_score': 2, 'selected': False, 'text': "<p>In my experience, no; you just have to properly mutex yourself when you write to those values, or structure your program such that the threads will stop before they need to access data that depends on another thread's actions.  My project, x264, uses this method; threads share an enormous amount of data but the vast majority of it doesn't need mutexes because its either read-only or a thread will wait for the data to become available and finalized before it needs to access it.</p>\n\n<p>Now, if you have many threads that are all heavily interleaved in their operations (they depend on each others' output on a very fine-grained level), this may be a lot harder--in fact, in such a case I'd consider revisiting the threading model to see if it can possibly be done more cleanly with more separation between threads.</p>\n"}, {'answer_id': 78221, 'author': 'Don Neufeld', 'author_id': 13097, 'author_profile': 'https://Stackoverflow.com/users/13097', 'pm_score': 5, 'selected': False, 'text': '<p>As long as you are using locks to control access to the variable, you do not need volatile on it.  In fact, if you\'re putting volatile on any variable you\'re probably already wrong.</p>\n\n<p><a href="http://web.archive.org/web/20190219170904/https://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/" rel="nofollow noreferrer">https://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/</a></p>\n'}, {'answer_id': 78228, 'author': 'Branan', 'author_id': 13894, 'author_profile': 'https://Stackoverflow.com/users/13894', 'pm_score': 0, 'selected': False, 'text': "<p>Volatile would only be useful if you need absolutely no delay between when one thread writes something and another thread reads it. Without some sort of lock, though, you have no idea of <em>when</em> the other thread wrote the data, only that it's the most recent possible value.</p>\n\n<p>For simple values (int and float in their various sizes) a mutex might be overkill if you don't need an explicit synch point. If you don't use a mutex or lock of some sort, you should declare the variable volatile. If you use a mutex you're all set.</p>\n\n<p>For complicated types, you must use a mutex. Operations on them are non-atomic, so you could read a half-changed version without a mutex.</p>\n"}, {'answer_id': 166767, 'author': 'jakobengblom2', 'author_id': 23054, 'author_profile': 'https://Stackoverflow.com/users/23054', 'pm_score': 4, 'selected': True, 'text': '<p>I think one very important property of volatile is that it makes the variable be written to memory when modified, and reread from memory each time it accessed.  The other answers here mix volatile and synchronization, and it is clear from some other answers than this that volatile is NOT a sync primitive (credit where credit is due). </p>\n\n<p>But unless you use volatile, the compiler is free to cache the shared data in a register for any length of time... if you want your data to be written to be predictably written to actual memory and not just cached in a register by the compiler at its discretion, you will need to mark it as volatile.  Alternatively, if you only access the shared data after you have left a function modifying it, you might be fine.  But I would suggest not relying on blind luck to make sure that values are written back from registers to memory. </p>\n\n<p>Especially on register-rich machines (i.e., not x86), variables can live for quite long periods in registers, and a good compiler can cache even parts of structures or entire structures in registers.  So you should use volatile, but for performance, also copy values to local variables for computation and then do an explicit write-back. Essentially, using volatile efficiently means doing a bit of load-store thinking in your C code. </p>\n\n<p>In any case, you positively have to use some kind of OS-level provided sync mechanism to create a correct program. </p>\n\n<p>For an example of the weakness of volatile, see my Decker\'s algorithm example at <a href="http://jakob.engbloms.se/archives/65" rel="noreferrer">http://jakob.engbloms.se/archives/65</a>, which proves pretty well that volatile does not work to synchronize. </p>\n'}, {'answer_id': 559133, 'author': 'cmcginty', 'author_id': 64313, 'author_profile': 'https://Stackoverflow.com/users/64313', 'pm_score': 2, 'selected': False, 'text': '<p>NO. </p>\n\n<p><code>Volatile</code> is only required when reading a memory location that can change independently of the CPU read/write commands. In the situation of threading, the CPU is in full control of read/writes to memory for each thread, therefore the compiler can assume the memory is coherent and optimizes the CPU instructions to reduce unnecessary memory access.</p>\n\n<p>The primary usage for <code>volatile</code> is for accessing memory-mapped I/O. In this case, the underlying device can change the value of a memory location independently from CPU. If you do not use <code>volatile</code> under this condition, the CPU may use a previously cached memory value, instead of reading the newly updated value.</p>\n'}, {'answer_id': 784840, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 4, 'selected': False, 'text': "<p>The answer is absolutely, unequivocally, NO. You do not need to use 'volatile' in addition to proper synchronization primitives. Everything that needs to be done are done by these primitives.</p>\n\n<p>The use of 'volatile' is neither necessary nor sufficient. It's not necessary because the proper synchronization primitives are sufficient. It's not sufficient because it only disables some optimizations, not all of the ones that might bite you. For example, it does not guarantee either atomicity or visibility on another CPU.</p>\n\n<blockquote>\n  <p>But unless you use volatile, the compiler is free to cache the shared data in a register for any length of time... if you want your data to be written to be predictably written to actual memory and not just cached in a register by the compiler at its discretion, you will need to mark it as volatile. Alternatively, if you only access the shared data after you have left a function modifying it, you might be fine. But I would suggest not relying on blind luck to make sure that values are written back from registers to memory.</p>\n</blockquote>\n\n<p>Right, but even if you do use volatile, the CPU is free to cache the shared data in a write posting buffer for any length of time. The set of optimizations that can bite you is not precisely the same as the set of optimizations that 'volatile' disables. So if you use 'volatile', you <em>are</em> relying on blind luck.</p>\n\n<p>On the other hand, if you use sychronization primitives with defined multi-threaded semantics, you are guaranteed that things will work. As a plus, you don't take the huge performance hit of 'volatile'. So why not do things that way?</p>\n"}, {'answer_id': 3770959, 'author': 'Stephen Nuchia', 'author_id': 455224, 'author_profile': 'https://Stackoverflow.com/users/455224', 'pm_score': -1, 'selected': False, 'text': '<p>Some people obviously are assuming that the compiler treats the synchronization calls as memory barriers.  "Casey" is assuming there is exactly one CPU.</p>\n\n<p>If the sync primitives are external functions and the symbols in question are visible outside the compilation unit (global names, exported pointer, exported function that may modify them) then the compiler will treat them -- or any other external function call -- as a memory fence with respect to all externally visible objects.</p>\n\n<p>Otherwise, you are on your own.  And volatile may be the best tool available for making the compiler produce correct, fast code.  It generally won\'t be portable though, when you need volatile and what it actually does for you depends a lot on the system and compiler.</p>\n'}, {'answer_id': 4074757, 'author': 'Adam Soffer', 'author_id': 352241, 'author_profile': 'https://Stackoverflow.com/users/352241', 'pm_score': -1, 'selected': False, 'text': "<p>Variables that are shared among threads should be declared 'volatile'. This tells the\ncompiler that when one thread writes to such variables, the write should be to memory\n(as opposed to a register).</p>\n"}, {'answer_id': 8120128, 'author': 'IOException', 'author_id': 230803, 'author_profile': 'https://Stackoverflow.com/users/230803', 'pm_score': 2, 'selected': False, 'text': '<p>There is a widespread notion that the keyword volatile is good for multi-threaded programming. </p>\n\n<p>Hans Boehm <a href="http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2016.html" rel="nofollow">points out</a> that there are only three portable uses for volatile:</p>\n\n<ul>\n<li><em>volatile</em> may be used to mark local variables in the same scope as a setjmp whose value should be preserved across a longjmp. It is unclear what fraction of such uses would be slowed down, since the atomicity and ordering constraints have no effect if there is no way to share the local variable in question. (It is even unclear what fraction of such uses would be slowed down by requiring all variables to be preserved across a longjmp, but that is a separate matter and is not considered here.)</li>\n<li><em>volatile</em> may be used when variables may be "externally modified", but the modification in fact is triggered synchronously by the thread itself, e.g. because the underlying memory is mapped at multiple locations.</li>\n<li>A <em>volatile</em> sigatomic_t may be used to communicate with a signal handler in the same thread, in a restricted manner. One could consider weakening the requirements for the sigatomic_t case, but that seems rather counterintuitive.</li>\n</ul>\n\n<p>If you are <em>multi-threading</em> for the sake of speed, slowing down code is definitely not what you want. For multi-threaded programming, there two key issues that volatile is often mistakenly thought to address:</p>\n\n<ul>\n<li><em>atomicity</em></li>\n<li><em>memory consistency</em>, i.e. the order of a thread\'s operations as seen by another thread.</li>\n</ul>\n\n<p>Let\'s deal with (1) first. Volatile does not guarantee atomic reads or writes. For example, a volatile read or write of a 129-bit structure is not going to be atomic on most modern hardware. A volatile read or write of a 32-bit int is atomic on most modern hardware, but <em>volatile has nothing to do with it</em>. It would likely be atomic without the volatile. The atomicity is at the whim of the compiler. There\'s nothing in the C or C++ standards that says it has to be atomic.</p>\n\n<p>Now consider issue (2). Sometimes programmers think of volatile as turning off optimization of volatile accesses. That\'s largely true in practice. But that\'s only the volatile accesses, not the non-volatile ones. Consider this fragment:</p>\n\n<pre><code> volatile int Ready;       \n\n    int Message[100];      \n\n    void foo( int i ) {      \n\n        Message[i/10] = 42;      \n\n        Ready = 1;      \n\n    }\n</code></pre>\n\n<p>It\'s trying to do something very reasonable in multi-threaded programming: write a message and then send it to another thread. The other thread will wait until Ready becomes non-zero and then read Message. Try compiling this with "gcc -O2 -S" using gcc 4.0, or icc. Both will do the store to Ready first, so it can be overlapped with the computation of i/10. The reordering is not a compiler bug. It\'s an aggressive optimizer doing its job.</p>\n\n<p>You might think the solution is to mark all your memory references volatile. That\'s just plain silly. As the earlier quotes say, it will just slow down your code. Worst yet, it might not fix the problem. Even if the compiler does not reorder the references, the hardware might. In this example, x86 hardware will not reorder it. Neither will an Itanium(TM) processor, because Itanium compilers insert memory fences for volatile stores. That\'s a clever Itanium extension. But chips like Power(TM) will reorder. What you really need for ordering are <em>memory fences</em>, also called <em>memory barriers</em>. A memory fence prevents reordering of memory operations across the fence, or in some cases, prevents reordering in one direction.Volatile has nothing to do with memory fences.</p>\n\n<p>So what\'s the solution for multi-threaded programming? Use a library or language extension that implements the atomic and fence semantics. When used as intended, the operations in the library will insert the right fences. Some examples:</p>\n\n<ul>\n<li>POSIX threads</li>\n<li>Windows(TM) threads</li>\n<li>OpenMP</li>\n<li>TBB</li>\n</ul>\n\n<p>Based on <a href="http://software.intel.com/en-us/blogs/2007/11/30/volatile-almost-useless-for-multi-threaded-programming/" rel="nofollow">article by Arch Robison (Intel)</a></p>\n'}, {'answer_id': 36608264, 'author': 'David Schwartz', 'author_id': 721269, 'author_profile': 'https://Stackoverflow.com/users/721269', 'pm_score': -1, 'selected': False, 'text': "<p>No.</p>\n\n<p>First, <code>volatile</code> is not necessary. There are numerous other operations that provide guaranteed multithreaded semantics that don't use <code>volatile</code>. These include atomic operations, mutexes, and so on.</p>\n\n<p>Second, <code>volatile</code> is not sufficient. The C standard does not provide any guarantees about multithreaded behavior for variables declared <code>volatile</code>.</p>\n\n<p>So being neither necessary nor sufficient, there's not much point in using it.</p>\n\n<p>One exception would be particular platforms (such as Visual Studio) where it does have documented multithreaded semantics.</p>\n"}, {'answer_id': 46987303, 'author': 'Patrick Pan', 'author_id': 2376062, 'author_profile': 'https://Stackoverflow.com/users/2376062', 'pm_score': 0, 'selected': False, 'text': '<p>The underlying reason is that the C language semantic is based upon a <strong>single-threaded abstract machine</strong>. And the compiler is within its own right to transform the program as long as the program\'s \'observable behaviors\' on the abstract machine stay unchanged. It can merge adjacent or overlapping memory accesses, redo a memory access multiple times (upon register spilling for example), or simply discard a memory access, if it thinks the program\'s behaviors, when executed in <strong>a single thread</strong>, doesn\'t change. Therefore as you may suspect, the behaviors <strong>do</strong> change if the program is actually supposed to be executing in a multi-threaded way.</p>\n\n<p>As Paul Mckenney pointed out in a famous <a href="http://elixir.free-electrons.com/linux/latest/source/Documentation/memory-barriers.txt#L264" rel="nofollow noreferrer" title="memory-barriers.txt">Linux kernel document</a>:</p>\n\n<blockquote>\n  <p>It _must_not_ be assumed that the compiler will do what you want\n       with memory references that are not protected by READ_ONCE() and\n       WRITE_ONCE().  Without them, the compiler is within its rights to\n       do all sorts of "creative" transformations, which are covered in\n       the COMPILER BARRIER section.</p>\n</blockquote>\n\n<p>READ_ONCE() and WRITE_ONCE() are defined as volatile casts on referenced variables. Thus:</p>\n\n<pre><code>int y;\nint x = READ_ONCE(y);\n</code></pre>\n\n<p>is equivalent to:</p>\n\n<pre><code>int y;\nint x = *(volatile int *)&amp;y;\n</code></pre>\n\n<p>So, unless you make a \'volatile\' access, you are not assured that the access happens <strong>exactly once</strong>, no matter what synchronization mechanism you are using. Calling an external function (pthread_mutex_lock for example) may force the compiler do memory accesses to global variables. But this happens only when the compiler fails to figure out whether the external function changes these global variables or not. Modern compilers employing sophisticated inter-procedure analysis and link-time optimization make this trick simply useless.</p>\n\n<p>In summary, you should mark variables shared by multiple threads volatile or access them using volatile casts.</p>\n\n<hr>\n\n<p>As Paul McKenney has also pointed out:</p>\n\n<blockquote>\n  <p>I have seen the glint in their eyes when they discuss optimization techniques that you would not want your children to know about!</p>\n</blockquote>\n\n<hr>\n\n<p>But see what happens to <strong>C11/C++11</strong>.</p>\n'}, {'answer_id': 58935671, 'author': 'Ciro Santilli OurBigBook.com', 'author_id': 895245, 'author_profile': 'https://Stackoverflow.com/users/895245', 'pm_score': 1, 'selected': False, 'text': '<p><strong>POSIX 7 guarantees that functions such as <code>pthread_lock</code> also synchronize memory</strong></p>\n\n<p><a href="https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11" rel="nofollow noreferrer">https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_11</a> "4.12 Memory Synchronization" says:</p>\n\n<blockquote>\n  <p>The following functions synchronize memory with respect to other threads:</p>\n\n<pre><code>pthread_barrier_wait()\npthread_cond_broadcast()\npthread_cond_signal()\npthread_cond_timedwait()\npthread_cond_wait()\npthread_create()\npthread_join()\npthread_mutex_lock()\npthread_mutex_timedlock()\npthread_mutex_trylock()\npthread_mutex_unlock()\npthread_spin_lock()\npthread_spin_trylock()\npthread_spin_unlock()\npthread_rwlock_rdlock()\npthread_rwlock_timedrdlock()\npthread_rwlock_timedwrlock()\npthread_rwlock_tryrdlock()\npthread_rwlock_trywrlock()\npthread_rwlock_unlock()\npthread_rwlock_wrlock()\nsem_post()\nsem_timedwait()\nsem_trywait()\nsem_wait()\nsemctl()\nsemop()\nwait()\nwaitpid()\n</code></pre>\n</blockquote>\n\n<p>Therefore if your variable is guarded between <code>pthread_mutex_lock</code> and <code>pthread_mutex_unlock</code> then it does not need further synchronization as you might attempt to provide with <code>volatile</code>.</p>\n\n<p>Related questions:</p>\n\n<ul>\n<li><a href="https://stackoverflow.com/questions/3208060/does-guarding-a-variable-with-a-pthread-mutex-guarantee-its-also-not-cached">Does guarding a variable with a pthread mutex guarantee it&#39;s also not cached?</a></li>\n<li><a href="https://stackoverflow.com/questions/24137964/does-pthread-mutex-lock-contains-memory-fence-instruction">Does pthread_mutex_lock contains memory fence instruction?</a></li>\n</ul>\n'}]
['https://Stackoverflow.com/questions/78172', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/11688/']