本文介绍了Jon关于线程的文章:等待和脉冲的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 限时删除!! 也许现在已经很晚了,但我正在阅读Jon关于 线程的文章,特别是如何使用Monitor.Wait()和Monitor.Pulse (), 并且有一些东西没有下沉。有问题的代码 看起来像这样: public class ProducerConsumer { readonly object listLock = new object(); Queue queue = new Queue(); public void Produce(object o) { lock(listLock) { queue.Enqueue(o); if(queue.Count == 1) { Monitor.Pulse( listLock); } } } 公共对象Consume() { lock(listLock) { while(queue.Count == 0) { Monitor.Wait(listLock); } 返回queue.Dequeue(); } } } 我不明白的是为什么Consume()方法中的代码是封闭在一个锁(listLock)中的?这不会造成僵局吗? I.e。: 消费在listLock上获取一个锁,然后调用Monitor.Wait等待一个脉冲的。然后Produce()尝试生成一些东西,但是等待它的lock(listLock)等等。测试,等待Consume()以 释放它对listLock的锁定,当然,它永远不会这样做, ,因为它正在等待Produce()脉冲它。 我知道Jon运行测试他自己的代码:)所以我知道这是有效的, 但是我看不出它可以工作。 有人可以解释一下吗?Maybe it''s just late in my day, but I''m reading Jon''s article onthreading, in particular how to use Monitor.Wait() and Monitor.Pulse(),and there''s something that''s not sinking in. The code in questionlooks like this:public class ProducerConsumer{readonly object listLock = new object();Queue queue = new Queue();public void Produce(object o){lock (listLock){queue.Enqueue(o);if (queue.Count==1){Monitor.Pulse(listLock);}}}public object Consume(){lock (listLock){while (queue.Count==0){Monitor.Wait(listLock);}return queue.Dequeue();}}}What I don''t understand is why the code in the Consume() method isenclosed in a lock (listLock)? Won''t this create a deadlock? I.e.:Consume acquires a lock on listLock, then calls Monitor.Wait to waitfor a pulse. Produce() then attempts to produce something, but getsstuck waiting on its "lock (listLock)" test, waiting for Consume() torelease its lock on listLock, which, of course, it will never do,because it''s waiting for Produce() to pulse it.I know that Jon runs tests his own code :) so I know that this works,but I can''t see how it could work.Could someone please explain?推荐答案 是的。 这就是为什么Jon在挂锁或挂锁上做了这样的努力 listLock在这种情况下.. 因为他有一个readonly listLock,它(有点)是静态的并且会锁定(和 队列)尝试调用任何方法的任何线程。 或者我理解它...我错过了什么? 哦,你有垃圾邮件中某处的邮件... - Michael SYes.This is why Jon have made such an effort in writing on ''padlocks'' or alistLock in this case..As he has a readonly listLock, it is (somewhat) static and will lock (andqueue) any thread that tries to call any methods.Or so I understand it... What am I missing?Oh, You got a mail somewhere in your spam...- Michael S 这篇关于Jon关于线程的文章:等待和脉冲的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 1403页,肝出来的.. 09-07 18:41