Home
Map
volatile ExampleUnderstand the volatile keyword and its purpose in threaded programs.
C#
This page was last reviewed on Nov 17, 2022.
Volatile. This modifier reduces concurrency issues. Compilers reorder instructions in blocks. This improves performance but causes problems for concurrent threads.
Keyword notes. Volatile provides a way to affect how the compiler optimizes accesses to a field. It can fix certain kinds of bugs in threaded programs.
lock
Example. This example would function correctly without the volatile modifier. It illustrates the concept of the volatile keyword, not to provide a real-world example.
Next There are 2 static fields. One is an object reference of string type. The other is a volatile bool value type.
Then In the Main method, a new thread is created, and the SetVolatile method is invoked. In SetVolatile, both the fields are set.
ThreadStart
using System; using System.Threading; class Program { static string _result; static volatile bool _done; static void SetVolatile() { // Set the string. _result = "Dot Net Perls"; // The volatile field must be set at the end of this method. _done = true; } static void Main() { // Run the above method on a new thread. new Thread(new ThreadStart(SetVolatile)).Start(); // Wait a while. Thread.Sleep(200); // Read the volatile field. if (_done) { Console.WriteLine(_result); } } }
Dot Net Perls
Program info. Why is the bool volatile? First, the logic in this program is correct even without the volatile modifier on the bool.
Detail Compilers introduce extra, hidden complexity—they use a lot of optimizations.
And Some of these optimizations reorder loads and stores from variables. So conceptually the program could be incorrect.
Thus The order of assignments could change. When multiple threads execute at once, this can cause serious problems.
Detail Volatile tells the compiler not to change the order of accesses to the field.
Flags. The example demonstrates a volatile field used as a flag. The bool type is commonly used as a flag. So when the flag is set to true, you can take other action on that variable.
Performance. Can volatile fields cause a performance problem? In some cases, this may happen. It is probably a better idea not to use volatile in your programs at all.
A summary. Volatile restrict the optimizations the compiler makes regarding loads and stores into the field. This helps threaded programs.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Nov 17, 2022 (simplify).
Home
Changes
© 2007-2024 Sam Allen.