volatile and multithread

Mar 3 2013 3:04 AM

Hi!

What is the very function of volatile keyword? As the doc in MSDN mentioned, it is a modifier to indicate a field might be modified by multiple threads that are executing at the same time. But the following program which has two threads modifying a field modified by volatile  will still be wrong in sometimes. The result is the same as that without volatile.
Anyone would explain it for me?
Thanks in advance!

Raymond

P.s. the program list:

using System;
using System.Threading;

namespace ShareVariable
{
    class varyValue
    {
        private volatile int v = 0;
        public void IncVariable()
        {
            for (int i = 0; i < 100; i++)
            {
                v++;
                Thread.Sleep(10);
            }
        }
        public void DecVariable()
        {
            for (int i = 0; i < 90; i++)
            {
                v--;
                Thread.Sleep(10);
            }
        }
        public void disp()
        {
            Console.WriteLine("v is {0}.", this.v);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            varyValue vv = new varyValue();
            vv.disp();
            Thread t1 = new Thread(vv.IncVariable);
            Thread t2 = new Thread(vv.DecVariable);
            t1.Start();
            t2.Start();
            t1.Join();
            t2.Join();
            vv.disp();
            Console.ReadKey();
        }
    }
}


Answers (2)