Volatile variable

Volatile is an additive in the declaration of variables in programming languages ​​such as C, C , Java or C #.

In C and C is specified by this Typqualifikator that the value of the variable may change at any time, for example by other processes, threads, or even external hardware. When generating the machine code of a program written in C or C program, the Marking a variable as volatile prevents one in this case, the functionality affecting optimization so that the program always accesses the hardware actually present in the value.

On the contrary, variables are identified by # in volatile Java and C accessed from different threads in order to synchronize the visibility. With volatile marked variables are not cached in Java (eg registers). This ensures that even with access from multiple threads, the correct value is read. Volatile ensures in Java not for mutual exclusion and not replaced thus synchronization mechanisms (eg, locks or semaphores ).

Example in C

Without the addition of volatile, the compiler could replace the loop in the following program segment by a simple loop and optimize away the variable status:

Static volatile int status = 0;   poll_status void (void) {      while ( status == 0)         ; } References

  • Programming language element
807581
de