详细解析C#多线程同步事件及等待句柄
最近捣鼓了一下多线程的同步问题,发现其实C#关于多线程同步事件处理还是很灵活,这里主要写一下,自己测试的一些代码,涉及到了AutoResetEvent和ManualResetEvent,当然还有也简要提了一下System.Threading.WaitHandle.WaitOne、System.Threading.WaitHandle.WaitAny和System.Threading.WaitHandle.WaitAll,下面我们一最初学者的角度来看,多线程之间的同步。
假设有这样的一个场景,主线程开了一个子线程,让子线程等着,等主线程完成了某件事情时再通知子线程去往下执行,这里关键就在于这个怎让子线程等着,主线程怎通知子线程,一般情况下我们不难想到用一个公共变量,于是咱们就有了下面的代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Threading; namespaceAutoResetEventTest { classClass1 { staticboolflag=true; staticvoidDoWork() { Console.WriteLine("workerthreadstarted,nowwaitingonevent..."); while(flag) { } Console.WriteLine("workerthreadreactivated,nowexiting..."); } staticvoidMain() { Console.WriteLine("mainthreadstartingworkerthread..."); Threadt=newThread(DoWork); t.Start(); Console.WriteLine("mainthradsleepingfor1second..."); Thread.Sleep(1000); Console.WriteLine("mainthreadsignalingworkerthread..."); flag=false; } } }
虽然目的达到了,但是看着这代码就纠结,下面该是我们的主角上场了,AutoResetEvent和ManualResetEvent,关于这两者我们暂且认为是差不多了,稍后我会介绍他们的不同,这里以AutoResetEvent为例,其实很多官方的说法太过于抽象,这里通俗地讲,可以认为AutoResetEvent就是一个公共的变量(尽管它是一个事件),创建的时候可以设置为false,然后在要等待的线程使用它的WaitOne方法,那么线程就一直会处于等待状态,只有这个AutoResetEvent被别的线程使用了Set方法,也就是要发通知的线程使用了它的Set方法,那么等待的线程就会往下执行了,Set就是发信号,WaitOne是等待信号,只有发了信号,等待的才会执行。如果不发的话,WaitOne后面的程序就永远不会执行。好下面看用AutoResetEvent改造上面的程序:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Threading; namespaceAutoResetEventTest { classClass2 { staticAutoResetEventmEvent=newAutoResetEvent(false); //staticManualResetEventmEvent=newManualResetEvent(false); staticvoidDoWork() { Console.WriteLine("workerthreadstarted,nowwaitingonevent..."); mEvent.WaitOne(); Console.WriteLine("workerthreadreactivated,nowexiting..."); } staticvoidMain() { Console.WriteLine("mainthreadstartingworkerthread..."); Threadt=newThread(DoWork); t.Start(); Console.WriteLine("mainthradsleepingfor1second..."); Thread.Sleep(1000); Console.WriteLine("mainthreadsignalingworkerthread..."); mEvent.Set(); } } }
这时代码是不是清爽多了,这里其实你还会看到,把上面的AutoResetEvent换成ManualResetEvent也是没有问题的,那么它两之间的区别是什么呢?个人认为它们最大的区别在于,无论何时,只要AutoResetEvent激活线程,它的状态将自动从终止变为非终止。相反,ManualResetEvent允许它的终止状态激活任意多个线程,只有当它的Reset方法被调用时才还原到非终止状态。开下面的代码:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Threading; namespaceAutoResetEventTest { classClass3 { staticAutoResetEventmEvent=newAutoResetEvent(false); //staticManualResetEventmEvent=newManualResetEvent(false); staticvoidDoWork() { Console.WriteLine("workerthreadstarted,nowwaitingonevent..."); for(inti=0;i<3;i++) { mEvent.WaitOne(); //mEvent.Reset(); Console.WriteLine("workerthreadreactivated,nowexiting..."); } } staticvoidMain() { Console.WriteLine("mainthreadstartingworkerthread..."); Threadt=newThread(DoWork); t.Start(); for(inti=0;i<3;i++) { Thread.Sleep(1000); Console.WriteLine("mainthreadsignalingworkerthread..."); mEvent.Set(); } } } }
如果你想仅仅把AutoResetEvent换成ManualResetEvent的话,你发现输出就会乱套了,为什么呢?
假如有autoevent.WaitOne()和manualevent.WaitOne(),当线程得到信号后都得以继续执行。差别就在调用后,autoevent.WaitOne()每次只允许一个线程进入,当某个线程得到信号(也就是有其他线程调用了autoevent.Set()方法后)后,autoevent会自动又将信号置为不发送状态,则其他调用WaitOne的线程只有继续等待,也就是说,autoevent一次只唤醒一个线程。而manualevent则可以唤醒多个线程,当某个线程调用了set方法后,其他调用waitone的线程获得信号得以继续执行,而manualevent不会自动将信号置为不发送,也就是说,除非手工调用了manualevent.Reset()方法,否则manualevent将一直保持有信号状态,manualevent也就可以同时唤醒多个线程继续执行。
在上面代码中,如果将AutoResetEvent换成ManualResetEvent的话,只要要在waitone后面做下reset,就会达到同样的效果。
之后咱们再来个简单的例子:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Threading; namespaceAutoResetEventTest { classClass4 { publicstaticAutoResetEventmEvent=newAutoResetEvent(false); publicstaticvoidtrmain() { Threadtr=Thread.CurrentThread; Console.WriteLine("thread:waitingforanevent"); mEvent.WaitOne(); Console.WriteLine("thread:gotanevent"); for(intx=0;x<10;x++) { Thread.Sleep(1000); Console.WriteLine(tr.Name+":"+x); } } staticvoidMain(string[]args) { Threadthrd1=newThread(newThreadStart(trmain)); thrd1.Name="thread1"; thrd1.Start(); for(intx=0;x<10;x++) { Thread.Sleep(900); Console.WriteLine("Main:"+x); if(5==x)mEvent.Set(); } while(thrd1.IsAlive) { Thread.Sleep(1000); Console.WriteLine("Main:waitingforthreadtostop"); } } } }
是不是更有感觉了?之后咱来看看另外几个东东:
System.Threading.WaitHandle.WaitOne使线程一直等待,直到单个事件变为终止状态;
System.Threading.WaitHandle.WaitAny阻止线程,直到一个或多个指示的事件变为终止状态;
System.Threading.WaitHandle.WaitAll阻止线程,直到所有指示的事件都变为终止状态。
然后再来个例子,以WaitAll使用为例:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Threading; namespaceAutoResetEventTest { classother { staticvoidMain(string[]args) { RandomrandomGenerator=newRandom(); AutoResetEvent[]resets=newAutoResetEvent[5]; for(inti=0;i<5;i++) { resets[i]=newAutoResetEvent(false); intwTime=randomGenerator.Next(10)+1; workerw=newworker(wTime,resets[i]); Threadthrd1=newThread(newThreadStart(w.work)); thrd1.Start(); } WaitHandle.WaitAll(resets); Console.WriteLine("ALLworkerdone-mainexiting."); } } publicclassworker { publicstringname; publicintwTime; publicAutoResetEventmEvent; publicworker(intw,AutoResetEventm) { name=w.ToString(); wTime=w*1000; mEvent=m; } publicvoidwork() { Console.WriteLine(name+"workerthreadwaitingfor"+wTime+"...."); Thread.Sleep(wTime); Console.WriteLine(name+"workerthreadback..."); mEvent.Set(); } } }
简单来说就是,开了5个线程,每个线程随机休眠若干秒,都完成后通知主线程退出,这里就开了一个AutoResetEvent数组,主线程就WaitHandle.WaitAll(resets),子线程休眠完后就Set1个AutoResetEvent,最后都Set完后,主线程就会往下执行。最后最后再来个买书付款取货的例子,加深理解:
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Threading; namespaceAutoResetEventTest { classProgram { constintnumIterations=10; staticAutoResetEventmyResetEvent=newAutoResetEvent(false); staticAutoResetEventChangeEvent=newAutoResetEvent(false); //staticManualResetEventmyResetEvent=newManualResetEvent(false); //staticManualResetEventChangeEvent=newManualResetEvent(false); staticintnumber;//这是关键资源 staticvoidMain() { ThreadpayMoneyThread=newThread(newThreadStart(PayMoneyProc)); payMoneyThread.Name="付钱线程"; ThreadgetBookThread=newThread(newThreadStart(GetBookProc)); getBookThread.Name="取书线程"; payMoneyThread.Start(); getBookThread.Start(); for(inti=1;i<=numIterations;i++) { Console.WriteLine("买书线程:数量{0}",i); number=i; //Signalthatavaluehasbeenwritten. myResetEvent.Set(); //ChangeEvent.Set(); Thread.Sleep(10); } payMoneyThread.Abort(); getBookThread.Abort(); } staticvoidPayMoneyProc() { while(true) { myResetEvent.WaitOne(); //myResetEvent.Reset(); Console.WriteLine("{0}:数量{1}",Thread.CurrentThread.Name,number); ChangeEvent.Set(); } } staticvoidGetBookProc() { while(true) { ChangeEvent.WaitOne(); //ChangeEvent.Reset(); Console.WriteLine("{0}:数量{1}",Thread.CurrentThread.Name,number); Console.WriteLine("------------------------------------------"); //Thread.Sleep(0); } } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。