首页 > 其他 > 详细

互斥体

时间:2017-09-13 15:49:56      阅读:383      评论:0      收藏:0      [点我收藏+]

1.线程间同步

1.1线程间同步

  Metux中提供了WatiOne和ReleaseMutex来确保只有一个线程来访问共享资源,是不是跟Monitor很类似,下面我还是举个简单的例子,注意我并没有给Metux取名字。

    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 20; i++)
            {
                Thread t = new Thread(Run);
                t.Start();
            }
            Console.Read();
        }
        static int count = 0;
        static Mutex mutex = new Mutex();
        static void Run()
        {
            Thread.Sleep(100);
            mutex.WaitOne();
            Console.WriteLine("当前数字:{0},进程为:{1}", ++count, Thread.CurrentThread.GetHashCode());
            mutex.ReleaseMutex();
        }
    }

 

技术分享

1.2进程间同步

  这次我给Mutex取个名字叫cnblogs,把Console程序copy一份,然后看看真的能够实现进程同步吗?

技术分享

技术分享

2个进程,只有一个能运行成功.

2.Interlocked

  为多个线程共享变量提供共享操作

2.1Increment,Decrement

    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 20; i++)
            {
                Thread t = new Thread(Run);

                t.Start();
            }
            Thread.Sleep(3000);
            Console.WriteLine("最后数字:{0}", count);
            Console.Read();
        }
        static int count = 0;static void Run()
        {
            Thread.Sleep(100);
            //+1
            Console.WriteLine("当前数字:{0}", Interlocked.Increment(ref count));
            //-1
            Console.WriteLine("当前数字:{0}", Interlocked.Decrement(ref count));
        }
    }

 

技术分享

2.2还有Add,Exchange,CompareExchange等等

    class Program
    {
        static int count = 0;
        static void Main(string[] args)
        {
            Interlocked.Add(ref count, 20);
            Console.WriteLine("Add数字:{0}", count);//20
            Interlocked.Exchange(ref count, 100);
            Console.WriteLine("Exchange:{0}", count);//100
            Console.Read();
        }
    }

 

互斥体

原文:http://www.cnblogs.com/lgxlsm/p/7515264.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!