互斥体
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();
}
}
页:
[1]