欢迎来到天天文库
浏览记录
ID:39546465
大小:59.50 KB
页数:7页
时间:2019-07-05
《c# 线程同步: 详解lock,monitor,同步事件和等待句柄以及mutex》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、c#线程同步:详解lock,monitor,同步事件和等待句柄以及mutex对于引用类型和非线程安全的资源的同步处理,有四种相关处理:lock关键字,监视器(Monitor),同步事件和等待句柄,mutex类。Lock关键字本人愚钝,在以前编程中遇到lock的问题总是使用lock(this)一锁了之,出问题后翻看MSDN突然发现下面几行字:通常,应避免锁定public类型,否则实例将超出代码的控制范围。常见的结构lock(this)、lock(typeof(MyType))和lock("myLock")违反此准则:如果实例可以被公共访问,将出现lock(this)
2、问题。如果MyType可以被公共访问,将出现lock(typeof(MyType))问题。由于进程中使用同一字符串的任何其他代码将共享同一个锁,所以出现lock(“myLock”)问题。来看看lock(this)的问题:如果有一个类Class1,该类有一个方法用lock(this)来实现互斥:lock关键字比Monitor简洁,其实lock就是对Monitor的Enter和Exit的一个封装。另外Monitor还有几个常用的方法:TryEnter能够有效的决绝长期死等的问题,如果在一个并发经常发生,而且持续时间长的环境中使用TryEnter,可以有效防止死锁或者长
3、时间的等待。比如我们可以设置一个等待时间boolgotLock=Monitor.TryEnter(myobject,1000),让当前线程在等待1000秒后根据返回的bool值来决定是否继续下面的操作。Pulse以及PulseAll还有Wait方法是成对使用的,它们能让你更精确的控制线程之间的并发,MSDN关于这3个方法的解释很含糊,有必要用一个具体的例子来说明一下:usingSystem.Threading;publicclassProgram{staticobjectball=newobject();publicstaticvoidMain(){Threadt
4、hreadPing=newThread(ThreadPingProc);ThreadthreadPong=newThread(ThreadPongProc);threadPing.Start();threadPong.Start();}staticvoidThreadPongProc(){System.Console.WriteLine("ThreadPong:Hello!");lock(ball)for(inti=0;i<5;i++){System.Console.WriteLine("ThreadPong:Pong");Monitor.Pulse(ball);
5、Monitor.Wait(ball);}System.Console.WriteLine("ThreadPong:Bye!");}staticvoidThreadPingProc(){System.Console.WriteLine("ThreadPing:Hello!");lock(ball)for(inti=0;i<5;i++){System.Console.WriteLine("ThreadPing:Ping");Monitor.Pulse(ball);Monitor.Wait(ball);}System.Console.WriteLine("ThreadP
6、ing:Bye!");}}执行结果如下(有可能是ThreadPong先执行):ThreadPing:Hello!ThreadPing:PingThreadPong:Hello!ThreadPong:PongThreadPing:PingThreadPong:PongThreadPing:PingThreadPong:PongThreadPing:PingThreadPong:PongThreadPing:PingThreadPong:PongThreadPing:Bye!当threadPing进程进入ThreadPingProc锁定ball并调用Monitor.P
7、ulse(ball);后,它通知threadPong从阻塞队列进入准备队列,当threadPing调用Monitor.Wait(ball)阻塞自己后,它放弃了了对ball的锁定,所以threadPong得以执行。PulseAll与Pulse方法类似,不过它是向所有在阻塞队列中的进程发送通知信号,如果只有一个线程被阻塞,那么请使用Pulse方法。同步事件和等待句柄同步事件和等待句柄用于解决更复杂的同步情况,比如一个一个大的计算步骤包含3个步骤result=firstterm+secondterm+thirdterm,如果现在想写个多线程程序,同时计算firstter
8、m,sec
此文档下载收益归作者所有