利用原子操作加锁确保线程安全——Interlocked

作者:追风剑情 发布于:2017-9-19 17:39 分类:C#

这是官方例子 https://msdn.microsoft.com/zh-cn/library/system.threading.interlocked.aspx


using System;
using System.Threading;

namespace InterlockedExchange_Example
{
    class MyInterlockedExchangeExampleClass
    {
        //0 for false, 1 for true.
        private static int usingResource = 0;

        private const int numThreadIterations = 5;
        private const int numThreads = 10;

        static void Main()
        {
            Thread myThread;
            Random rnd = new Random();

            for (int i = 0; i < numThreads; i++)
            {
                myThread = new Thread(new ThreadStart(MyThreadProc));
                myThread.Name = String.Format("Thread{0}", i + 1);

                //等待一会再启动线程
                Thread.Sleep(rnd.Next(0, 1000));
                myThread.Start();
            }

            Console.ReadKey();
        }

        private static void MyThreadProc()
        {
            for (int i = 0; i < numThreadIterations; i++)
            {
                UseResource();
                //Wait 1 second before next attempt.
                Thread.Sleep(1000);
            }
        }

        //A simple method that denies reentrancy.
        static bool UseResource()
        {
            //第1个访问Exchange()的线程会返回0,之后usingResource被设成1
            //这里利用原子操作加锁,确保if里的代码不会被多个线程同时访问
            //优点: 原子操作基于CPU,非阻塞,比lock效率高
            if (0 == Interlocked.Exchange(ref usingResource, 1))
            {
                Console.WriteLine("{0} acquired the lock", Thread.CurrentThread.Name);

                //这里的代码是线程安全的
                //模拟处理一些工作
                Thread.Sleep(500);

                Console.WriteLine("{0} exiting lock", Thread.CurrentThread.Name);

                //usingResource被设成0(即,释放锁)
                Interlocked.Exchange(ref usingResource, 0);
                return true;
            }
            else
            {
                Console.WriteLine("   {0} was denied the lock", Thread.CurrentThread.Name);
                return false;
            }
        }
    }
}


运行效果

111111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号