三种锁
lock
c# 允许锁嵌套
lock (locker)lock (locker)lock (locker){// Do something...}
或者
Monitor.Enter (locker); Monitor.Enter (locker); Monitor.Enter (locker);// Do something...Monitor.Exit (locker); Monitor.Exit (locker); Monitor.Exit (locker);
死锁:
object locker1 = new object();object locker2 = new object();new Thread (() => {lock (locker1){Thread.Sleep (1000);lock (locker2); // Deadlock}}).Start();lock (locker2){Thread.Sleep (1000);lock (locker1); // Deadlock}
semaphore
class TheClub // No door lists!{static SemaphoreSlim _sem = new SemaphoreSlim (3); // Capacity of 3static void Main(){for (int i = 1; i <= 5; i++) new Thread (Enter).Start (i);}static void Enter (object id){Console.WriteLine (id + " wants to enter");_sem.Wait();Console.WriteLine (id + " is in!"); // Only three threadsThread.Sleep (1000 * (int) id); // can be here atConsole.WriteLine (id + " is leaving"); // a time._sem.Release();}}
三种restEvent
AutoResetsEvent
一对一
CountdownEvent
多个线程结束一个锁
static CountdownEvent _countdown = new CountdownEvent (3);static void Main(){new Thread (SaySomething).Start ("I am thread 1");new Thread (SaySomething).Start ("I am thread 2");new Thread (SaySomething).Start ("I am thread 3");_countdown.Wait(); // Blocks until Signal has been called 3 timesConsole.WriteLine ("All threads have finished speaking!");}static void SaySomething (object thing){Thread.Sleep (1000);Console.WriteLine (thing);_countdown.Signal();}
ManualResetEvent
一个线程结束多个锁
线程同步的类
继承自 ContextBoundObject,打上[Synchronization]特性
using System;using System.Threading;using System.Runtime.Remoting.Contexts;[Synchronization]public class AutoLock : ContextBoundObject{public void Demo(){Console.Write ("Start...");Thread.Sleep (1000); // We can't be preempted hereConsole.WriteLine ("end"); // thanks to automatic locking!}}public class Test{public static void Main(){AutoLock safeInstance = new AutoLock();new Thread (safeInstance.Demo).Start(); // Call the Demonew Thread (safeInstance.Demo).Start(); // method 3 timessafeInstance.Demo(); // concurrently.}}
