Main purposes of C # volatile Fields

Source: Internet
Author: User
Tags dot net
Introduction

The article describes the internals of volatile fields. I 've seen a lot of discussions in the Web regarding volatile fields. I 've saved med my own small research in this area, and here are some thoughts on this.

Volatile fields and memory barrier: a look inside

The two main purposes of C # volatile fields are:

  1. Introduce memory barriers for all access operations to these fields. in order to improve performance, CPUs store frequently accessible objects in the CPU cache. in the case of multi-threaded applications, this can cause problems. for instance, imagine a situation when a thread is constantly reading a Boolean value (read thread) and another one is responsible for updating this field (write thread ). now, if the OS will decide to run these two threads in different CPUs, it is possible that the update thread will change the value of the field on the cpu1 cache and the read thread will continue reading the value from the cpu2 cache. in other words, it will not get the change in thread1 until the cpu1 cache is invalidated. the situation can be worse if two threads update the value.

    Volatile fields introduce memory barriers, which means that the CPU will always read from and write to the virtual memory, but not to the CPU cache. nowadays, such CPU ubuntures as x86 and x64 have CPU cache coherency, which means that any change in the CPU cache of one processor will be propagated to other CPU caches. and, in its turn, it means that the JIT Compiler For the x86 and x64 platforms makes no difference between volatile and non-volatile fields (could t the one stated in item #2 ). also, multi-core CPUs usually have two levels of cache: the first level is shared between CPU cores, and the second one is not. but, such CPU ubuntures as itanium with a weak memory model does not have cache coherency, and thereforeVolatile Keyword and memory barriers play a significant role while designing multi-threaded applications. Therefore, I 'd recommend to always use Volatile And memory barriers even for x86 and x64 CPUs, because otherwise, you introduce CPU architecture affinity to your application.

    Note: You can also introduce memory barriers by using thread. volatileread / thread. volatilewrite (these two methods successfully replace the volatile keyword), thread. memorybarrier , or even with the C # lock keyword etc.

    Below are displayed two CPU ubuntures: itanium and AMD (Direct Connect architecture ). as we can see, in AMD's Direct Connect architecture, all processors are connected with each other, so we have memory coherence. in the itanium architecture, the CPUs are not connected with each other and they communicate with Ram through the system bus.

 

 

 

 

2. Prevents instructionReorderIng. For instance, consider we have a loop:

While (true) {If (myfield) {// do something}

}

 

In the case of a non-volatile field, during JIT compilation, due to performance considerations, the JIT Compiler Can Reorder Instructions In the following manner: If (myfield) {While (true) {// do something}

}

In case you plan to change Myfield From a separate thread, will there be a significant difference? Usually, it is recommended to use Lock Statement ( Monitor. Enter Or Monitor. Exit ), But if you change only one field within this block, then the volatile field will perform significantly better than Monitor Class.

 

So. That is the why sometimes we need volatile. But I still have a question about why JIT need reorder the instructions. Can anyone tell me why? Thanks a lot.

 

Below is the example show how is the volatile keyword happen.

Compilers use advanced Optimizations to reorder instructions in blocks. This improves performance but can cause problems for concurrent threads. optimizations such as code motion can cause these problems. To alleviate concurrency issues, you can useVolatileModifier on a field: this does not substitute for a locking construct, but can make some code more correct.

Lock statementkeywords

This C # article describes the volatile keyword. Volatile is used in threaded programs.

Example

 Before we begin, please note that this example isn't ideal in that it wocould function correctly without the volatile modifier. it serves only to define strate the concept of the volatile keyword, not to provide a real-world example.

In the example,There are two static fields-one field is a object reference of string type, and the other is a volatile bool value type. in the main method, a new thread is created, and the setvolatile method is invoked. in setvolatile, both the fields are set.

Program that uses volatile field [C #]
 
Using system;
 
Using system. Threading;
 
Class program {
Static string _ result;
 
StaticVolatileBool _ 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 );
 
}
 
}
 
}
 
 Output
Dot NET Perls

 Why is the bool volatile?First of all, the logic in this program is correct even without the volatile Modifier on the bool. however, compilers use a lot of optimizations, and some of these optimizations reorder loads and stores from variables.

When multiple threads execute at once,This can cause serious problems. please keep in mind that the volatile modifier does not force synchronization of loads and stores; instead it simply tells the compiler not to change the order of accesses to the field. by eliminating reordering optimizations, the Code becomes more predictable from a programmer's perspective.

Correction:Thanks to Robert paveza for writing in with a correction to this article. It originally contained an incorrect statement-in programming terms, a bug.

Flags

The example in this article, adapted from the example in the C # specification itself, demonstrates the concept of a volatile field used as a flag. the bool type is very commonly used as a flag. so when the flag is set to true, You can take other action on that variable.

The C # programming language: Specification
Performance

Can volatile fields cause a performance problem if they are used too much? In some cases, this may happen. however, if you are using a volatile field that is accessed in a tight loop millions of times, you can copy it into a regular local variable and then use that local variable: this will provide a performance boost.

Local variable Field Optimization

Tip:

It's probably a better idea not to use volatile in your programs at all. 

Summary

 

 The volatile modifier in the C # programming language provides a way for you to restrict the optimizations the compiler makes regarding loads and stores into the field. typically, you will use volatile in multithreaded programs and with flag variables. the volatile keyword does not substitute for the lock statement; it merely restricts certain optimizations that cocould cause a multithreaded program to behave incorrectly.

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.