Volatile (keyword): Difference between revisions

Jump to navigation Jump to search
m
Bot: Replace deprecated source tag with syntaxhighlight
[unchecked revision][unchecked revision]
(Add link to volatile considered harmful)
m (Bot: Replace deprecated source tag with syntaxhighlight)
Line 5:
The <code>volatile</code> keyword can be used in type definitions as well as function arguments, variable definitions and typecasts. Similar to the <code>const</code> keyword, it either makes the variable itself or the data it points to <code>volatile</code>, or both.
 
<sourcesyntaxhighlight lang="c">
/* Ensures the changes to/reads from x are always performed */
volatile int x;
Line 22:
volatile int * volatile ptr;
int volatile * volatile ptr;
</syntaxhighlight>
</source>
 
== Examples ==
Line 49:
This example is supposed to poll a byte until it is <code>0</code> (e.g. waiting for a [[Spinlock]] to be released). Obviously another thread is supposed to change that memory, but since the compiler has no clue about this, we need to ensure that the code isn't optimized away in any case:
 
<sourcesyntaxhighlight lang="c">
typedef unsigned char * spin_lock;
/* Should be defined as '''typedef volatile unsigned char * spin_lock;'''
Line 72:
}
}
</syntaxhighlight>
</source>
 
=== Dereferencing memory ===
Line 78:
This is an example of code that is supposed to touch a piece of memory (e.g. to make it become resident or to check if it's valid and doesn't raise a page fault):
 
<sourcesyntaxhighlight lang="c">
static void touch_mem(void *ptr)
{
Line 88:
*data = *data;
}
</syntaxhighlight>
</source>
 
Also see the [[APIC#IO_APIC_Configuration|APIC example code]] where the <code>volatile</code> keyword is crucial (reading/writing to hardware registers).
Cookies help us deliver our services. By using our services, you agree to our use of cookies.

Navigation menu