C# Monitor.pulsell()中需要的帮助
谁能给我解释一下处理Monitor.pulsell()的简单示例吗?我已经从stackoverflow中学习了一些示例。由于我是初学者,我觉得这些都超出了我的理解范围。C# Monitor.pulsell()中需要的帮助,c#,multithreading,C#,Multithreading,谁能给我解释一下处理Monitor.pulsell()的简单示例吗?我已经从stackoverflow中学习了一些示例。由于我是初学者,我觉得这些都超出了我的理解范围。Monitor.Wait()将始终等待脉冲 因此,原则是: 当有疑问时,Monitor.Pulse() 当仍有疑问时,Monitor.pulsell() 除此之外,我不知道你在问什么。你能详细说明一下吗 编辑: 您的总体布局应为: Monitor.Enter(lock); try { while(!done) {
Monitor.Wait()
将始终等待脉冲
因此,原则是:
Monitor.Pulse()
Monitor.pulsell()
您的总体布局应为:
Monitor.Enter(lock);
try
{
while(!done)
{
while(!ready)
{
Monitor.Wait(lock);
}
// do something, and...
if(weChangedState)
{
Monitor.Pulse(lock);
}
}
}
finally
{
Monitor.Exit(lock);
}
(展示互动)怎么样:
再发信号;当处理
监视器
(又称锁
)时,有两种类型的阻塞;这里有一个“就绪队列”,线程排队等待执行。在Console.WriteLine之后的一行(“池线程想要锁”)代码>池队列进入就绪队列。释放锁时,就绪队列中的线程可以获取锁
第二个队列用于需要唤醒的线程;调用Wait
将线程放置在第二个队列中(并临时释放锁)。调用pulsell
会将第二个队列中的所有线程移动到就绪队列中(Pulse
只移动一个线程),这样当池线程释放锁时,允许主线程再次拿起锁
这听起来很复杂(也许的确如此)——但并不像听起来那么糟糕。。。真的然而,线程代码总是很棘手,需要谨慎和清醒的头脑来处理。谢谢Marc。我看过你的几篇文章。它们都很好,很容易理解。非常感谢你发自内心。Marc有一个问题。这里的信号表示“我即将发布”?。谢谢John。我真的很感谢你。:)锁不会自动释放吗?还是我们需要明确地指定它?我是说Monitor.Exit(lock)?@Prabugoel如果使用lock(obj){}
,锁会自动释放。如果使用Monitor.Enter()
,则必须显式地Monitor.Exit()
。否则运行时如何知道何时释放锁<代码>锁定(obj)
只是进入和退出的简写。
static void Main()
{
object obj = new object();
Console.WriteLine("Main thread wants the lock");
lock (obj)
{
Console.WriteLine("Main thread has the lock...");
ThreadPool.QueueUserWorkItem(ThreadMethod, obj);
Thread.Sleep(1000);
Console.WriteLine("Main thread about to wait...");
Monitor.Wait(obj); // this releases and re-acquires the lock
Console.WriteLine("Main thread woke up");
}
Console.WriteLine("Main thread has released the lock");
}
static void ThreadMethod(object obj)
{
Console.WriteLine("Pool thread wants the lock");
lock (obj)
{
Console.WriteLine("Pool thread has the lock");
Console.WriteLine("(press return)");
Console.ReadLine();
Monitor.PulseAll(obj); // this signals, but doesn't release the lock
Console.WriteLine("Pool thread has pulsed");
}
Console.WriteLine("Pool thread has released the lock");
}