线程同步——volatile

作者:追风剑情 发布于:2017-9-26 10:48 分类:C#

volatile是控制单个变量线程同步的关键字

示例

using System;
using System.Threading;

namespace volatileTest
{
    class Program
    {
        //volatile关键字保证了同一时间只会有1条线程访问此变量
        //线程不会进行本地缓存(即,直接在共享内存里操作)
        static volatile int i = 0;
        //不能保证同一时间只有1条线程访问,可能导致变量的不一致性
        //线程会进行本地缓存(即,先在本地缓存上操作,然后再同步到主内存)
        static int j = 0;

        static void Main(string[] args)
        {
            Thread myThread;
            for (int i = 0; i < 5; i++)
            {
                myThread = new Thread(new ThreadStart(MyThreadProc));
                myThread.Name = String.Format("Thread{0}", i + 1);
                myThread.IsBackground = true;
                myThread.Start();
            }

            Console.ReadKey();
        }

        private static void MyThreadProc()
        {
            j++;
            i++;
            Console.WriteLine("{0} Read i={1}, j={2}", Thread.CurrentThread.Name, i, j);
        }
    }
}


运行测试

111111.png

官方在.NET中的实现代码

[MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
public static int VolatileRead(ref int address)
{
	int ret = address;
	MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
	return ret;
}

[MethodImplAttribute(MethodImplOptions.NoInlining)] // disable optimizations
public static void VolatileWrite(ref int address, int value)
{
	MemoryBarrier(); // Call MemoryBarrier to ensure the proper semantic in a portable way.
	address = value;
}

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号