Click here to Skip to main content
6,292,811 members and growing! (11,479 online)
Email Password   helpLost your password?
General Programming » Threads, Processes & IPC » Multi-threading     Advanced License: The Code Project Open License (CPOL)

Volatile fields in .NET: A look inside

By Vitaliy Liptchinsky

The article describes in detail volatile fields in .NET and how they work on different CPU architectures.
C# (C# 1.0, C# 2.0, C# 3.0), .NET (.NET 2.0, .NET 3.0, .NET 3.5), Win32, Win64, Dev
Posted:27 Nov 2008
Views:5,489
Bookmarked:15 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
22 votes for this article.
Popularity: 6.05 Rating: 4.51 out of 5

1
1 vote, 4.5%
2
2 votes, 9.1%
3
6 votes, 27.3%
4
13 votes, 59.1%
5

Introduction

The article describes the internals of volatile fields. I've seen a lot of discussions in the web regarding volatile fields. I've performed 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 architectures 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 (except 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 architectures as Itanium with a weak memory model does not have cache coherency, and therefore the volatile 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 architectures: 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 instruction reordering. 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 the 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 the Monitor class.

Special thanks

I would like to thank Stefan Repas from Microsoft for providing some helpful information on this topic.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Vitaliy Liptchinsky


Member
The views expressed in my articles are mine and do not necessarily reflect the views of my employer.

if(youWantToContactMe)
{
SendMessage(string.Format("{0}@{1}.com", "liptchinski_vit", "yahoo"));
}

More info in my LinkedIn profile:
http://www.linkedin.com/in/vitaliyliptchinsky
Occupation: Software Developer (Senior)
Company: bwin Interactive Entertainment AG
Location: Austria Austria

Other popular Threads, Processes & IPC articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 8 of 8 (Total in Forum: 8) (Refresh)FirstPrevNext
Generalok PinmemberDonsw16:59 8 Feb '09  
GeneralMy Vote 4 PinsupporterDrew Stainton14:08 27 Nov '08  
GeneralRe: My Vote 4 Pinmemberkornakar21:54 27 Nov '08  
GeneralRe: My Vote 4 Pinmemberstano19:32 29 Nov '08  
GeneralRe: My Vote 4 PinmemberVitaliy Liptchinsky4:08 30 Nov '08  
GeneralMessage Automatically Removed PinmemberTom110:31 27 Nov '08  
AnswerRe: My vote of 2 [modified] PinmemberNick Butler12:00 27 Nov '08  
GeneralRe: My vote of 2 PinmemberAliceYeh17:27 12 Jan '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 27 Nov 2008
Editor: Smitha Vijayan
Copyright 2008 by Vitaliy Liptchinsky
Everything else Copyright © CodeProject, 1999-2009
Web12 | Advertise on the Code Project