【发布时间】:2012-03-14 20:30:05
【问题描述】:
根据MSDN,Monitor.Wait():
释放对象上的锁并阻塞当前线程,直到它 重新获得锁。
然而,我所读到的关于 Wait() 和 Pulse() 的所有内容似乎都表明,仅仅释放另一个线程上的锁是不够的。我需要先调用 Pulse() 来唤醒等待的线程。
我的问题是为什么?等待 Monitor.Enter() 上的锁的线程在它被释放时才得到它。没有必要“唤醒他们”。它似乎打败了 Wait() 的用处。
例如。
static object _lock = new Object();
static void Main()
{
new Thread(Count).Start();
Sleep(10);
lock (_lock)
{
Console.WriteLine("Main thread grabbed lock");
Monitor.Pulse(_lock) //Why is this required when we're about to release the lock anyway?
}
}
static void Count()
{
lock (_lock)
{
int count = 0;
while(true)
{
Writeline("Count: " + count++);
//give other threads a chance every 10th iteration
if (count % 10 == 0)
Monitor.Wait(_lock);
}
}
}
如果我使用 Exit() 和 Enter() 而不是 Wait() 我可以这样做:
static object _lock = new Object();
static void Main()
{
new Thread(Count).Start();
Sleep(10);
lock (_lock) Console.WriteLine("Main thread grabbed lock");
}
static void Count()
{
lock (_lock)
{
int count = 0;
while(true)
{
Writeline("Count: " + count++);
//give other threads a chance every 10th iteration
if (count % 10 == 0)
{
Monitor.Exit(_lock);
Monitor.Enter(_lock);
}
}
}
}
【问题讨论】:
标签: c# multithreading synchronization