开发者

Difference between Wait() and Pulse()

MSDN (http://msdn.microsoft.com/en-us/library/aa332339(VS.71).aspx) says that wait "Release开发者_运维百科s the lock on an object and blocks the current thread until it reacquires the lock." This implies basically lock toggling (Releasing, giving another thread a chance to run, reacquiring lock). But isn't this what Pulse() does? The only slight difference with Pulse it permenantly signals for the lock to be acquired?

The C# threading guide (http://www.albahari.com/threading/part4.aspx#_Wait_and_Pulse) has a very good analogy:

"Think of it like an automatic car park: you queue first at the pay station to validate your ticket (the waiting queue); "

So with the MSDN description, that means that when releasing the lock and blocking (same as wait - lock toggling), one car goes through and then the barrier (the lock) comes down?


Monitor.Wait and Monitor.Pulse are about a specific pattern to support creation of condition variables over any reference object in .NET. Outside that specific pattern they are useless (or at least I've yet to see any such use).

The difference is:

  • Wait: releases the lock, waits for a pulse (from another thread of course) and then re-acquires the lock.
  • Pulse: releases the lock, signals one other thread waiting, and then re-acquires the lock.

It is that middle bit: wait verses signal that is the difference between the two methods, and that difference enables safe inter-thread signals. Summary: they are complementary parts that fit together to create something.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜