Volatile (keyword): Difference between revisions

m
Bot: Replace deprecated source tag with syntaxhighlight
[unchecked revision][unchecked revision]
m (Bot: Replace deprecated source tag with syntaxhighlight)
m (Bot: Replace deprecated source tag with syntaxhighlight)
 
Line 30:
This is an example of a function that is supposed to create a very short delay, but might be optimized away by the compiler entirely because to the optimizer this code seems redundant:
 
<sourcesyntaxhighlight lang="c">
static void some_delay(void)
{
Line 45:
}
}
</syntaxhighlight>
</source>
 
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:
Line 96:
Suppose you have one thread "A" that loops until another thread "B" wants thread "A" to terminate gracefully. They share a structure with a field "terminate" that thread "A" polls to see if another thread wants it to terminate. Unless that field or the entire structure is declared <code>volatile</code>, there's no guarantee that the code works as expected because the compiler/optimizer has no clue about that field being touched by someone else while looping. So it could generate code that reads the value once and caches it, resulting in an infinite loop. Use <code>volatile</code> to prevent wrong code being generated:
 
<sourcesyntaxhighlight lang="c">
typedef struct {
int terminate; /* Should be volatile int terminate; */
Line 117:
}
}
</syntaxhighlight>
</source>
 
== External Links ==