标签:互斥 mutex 共享 incr blog 数字 logs 共享变量 等等
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(); } }
这次我给Mutex取个名字叫cnblogs,把Console程序copy一份,然后看看真的能够实现进程同步吗?
2个进程,只有一个能运行成功.
为多个线程共享变量提供共享操作
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)); } }
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(); } }
标签:互斥 mutex 共享 incr blog 数字 logs 共享变量 等等
原文地址:http://www.cnblogs.com/lgxlsm/p/7515264.html