volatile (computer science)

from Wikipedia, the free encyclopedia

Volatile ( German  volatile, changeable ) is an addition to the declaration of variables in programming languages ​​such as C , C ++ , Java or C # .

In C and C ++, this qualifier specifies that the value of the variable can change at any time without explicit access in the source code. This happens, for example, through other processes , threads or external hardware. When generating the machine code from a program written in C or C ++, the identification of a variable as volatilean optimization that would impair functionality in this case prevents the program from always accessing the value actually present in the hardware.

In contrast, in Java and C # variables are volatilemarked with that are accessed by different threads in order to synchronize the visibility. With volatilemarked variables are not cached in Java (z. B. in registers ). This ensures that the correct value is read even when multiple threads are accessed. The addition volatiledoes not ensure mutual exclusion in Java and thus does not replace synchronization mechanisms (e.g. locks or semaphores ).

Examples in C

Without volatilethis, the compiler could replace the loop in the following program statusexcerpt with a simple endless loop and optimize away the variable :

static volatile int status;

void poll_status(void)
{
    status = 0;

    while (status == 0)
        /* do nothing */;
}

In the following example, volatilethe conditional statement with the greeting could be eliminated without an optimizing compiler.

#include <stdio.h>
#include <setjmp.h>

jmp_buf env;

int main ()
{
   volatile int status = 0;

   if (setjmp (env))
   {
      if (status == 1)
         puts ("Hello World");
      return 0;
   }

   status = 1;
   longjmp (env, 1);
}

Individual evidence

  1. Should volatile Acquire Atomicity and Thread Visibility Semantics? In: C ++ standards committee. April 21, 2006, accessed March 13, 2018 .
  2. ^ British Standards Institute (ed.): The C Standard. Incorporating Technical Corrigendum 1. (Includes the C Rationale. ISO / IEC 9899: 1999). John Wiley & Sons, Chichester 2003, ISBN 0-470-84573-2 , chapter 6.7.3.
  3. volatile (C # Reference). Microsoft, accessed March 13, 2018 .
  4. Christian Ullenboom: Java is also an island. The comprehensive manual. (Currently on Java 7). 10th updated edition. Galileo Press, Bonn 2011, ISBN 978-3-8362-1802-3 , Chapter 9.7.1. ( openbook.galileodesign.de ), accessed on January 30, 2012.