逖靖寒的世界

每天进步一点点

导航

今天突然理解了“volatile”

首先咱们可以看一下MSDN对volatile的定义:
The volatile keyword indicates that a field can be modified in the program by something such as the operating system, the hardware, or a concurrently executing thread.

The system always reads the current value of a volatile object at the point it is requested, even if the previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment.

The volatile modifier is usually used for a field that is accessed by multiple threads without using the lock statement to serialize access. Using the volatile modifier ensures that one thread retrieves the most up-to-date value written by another thread.

然后呢,咱们可以看到在Singleton模式中对多线程的优化

 1using System;
 2using System.Configuration;
 3
 4namespace HeadFirstDesignPatterns.Singleton.InterestRate
 5{
 6    /// <summary>
 7    /// Summary description for RateSingleton.
 8    /// </summary>

 9    public class RateSingleton
10    {
11        private volatile static RateSingleton uniqueInstance;
12        private static object syncRoot = new Object();
13
14        private double currentRate = 
15            Convert.ToDouble(ConfigurationSettings.AppSettings["CurrentInterestRate"]);
16
17        public double CurrentRate
18        {
19            get
20            {
21                return currentRate;
22            }

23            set
24            {
25                currentRate = value;
26            }

27        }

28
29        private RateSingleton()
30        {}
31
32        public static RateSingleton GetInstance()
33        {
34            //The approach below ensures that only one instance is created and only 
35            //when the instance is needed. Also, the uniqueInstance variable is 
36            //declared to be volatile to ensure that assignment to the instance variable 
37            //completes before the instance variable can be accessed. Lastly, 
38            //this approach uses a syncRoot instance to lock on, rather than 
39            //locking on the type itself, to avoid deadlocks.
40
41            if(uniqueInstance == null)
42            {
43                lock (syncRoot)
44                {
45                    if(uniqueInstance == null)
46                    {
47                        uniqueInstance = new RateSingleton();
48                    }

49                }

50            }

51            return uniqueInstance;
52        }

53    }

54}

55

posted on 2007-11-12 12:36  逖靖寒  阅读(5375)  评论(7编辑  收藏  举报