开发者

Thread switching and deadlock prevention problem

if there are two threads as producer/consumer is it good idea to have following line to prevent deadlocks. I'm aware of live locks but suppose they do a lot of work before calling this Wait() method:

// member variable
object _syncLock = new object();

开发者_如何学运维void Wait()
{
   lock (_syncLock)
      {
         Monitor.Pulse(_syncLock);
         Monitor.Wait(_syncLock);
      }
}

Here it's impossible both threads be in waiting state.


This seems overly complicated. Just handle your locking correctly in the first place, and avoid the issue. If you only have two threads, and they are trying to acquire the same, single lock (correctly), you shouldn't have deadlocks. A deadlock means there is something else occurring here.

That being said, if you have the option of using the TPL via .NET 4 (or the Rx Extensions on .NET 3.5), you might want to consider using BlockingCollection<T> instead. It's ideally suited to use in a producer/consumer scenario, and works in a lockless manner.


If your intention is to create a paired variant of the producer-consumer pattern then the sequence is Pulse before Wait for the producer and Wait before Pulse for the consumer. You can reference figure 5 in Joe Duffy's article on this. Howerver, keep in mind that since his implementation performs an unconditional Wait in the Enqueue method a ping-pong like effect will occur between the producer and the consumer. The queue, in his implementation, can only ever have one item per producer. So if that is your intention then this your ticket. Otherwise, you can adapt it as-is and apply some condition1 to the Wait in the Enqueue method to make it behave more like a real FIFO buffer.

However, like Reed, I question why BlockingCollection could not be used. This collection should be very efficient since it uses a lock-free strategy for the Add and Take methods. Of course, like I mentioned above, if you really want the paired variant then this collection will not meet your requirements and you will have to roll your own using Joe Duffy's as a starting point.

1Just remember to use a while loop instead of an if check before applying the wait. Monitor.Wait simply waits for a change in the lock state and nothing more so you have to recheck the wait condition.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜