Is there any deadlock in this code?

Consider a traditional manufacturing / consumer example. When a consumer checks for a non-zero buffer size, is there a need to signal other threads before waiting for a lock? Here is the code for the methods:

public void consume()
{
    lock(_lock)
    {
        while(buf.Count == 0)
        {
             // Is there any need to *Monitor.Pulse(_lock);* here?
             Monitor.Wait(_lock);
        }
        // Consume
    }
}

public void produce()
{
    lock(_lock)
    {
        // Produce
        buf.Insert(item);
        Monitor.PulseAll(_lock);
    }
}
+1
source share
1 answer

No, it will not be deadlock:

  • As soon as the manufacturer can get the lock, he quickly releases it (the impulse does not interrupt the manufacturer)
  • when a consumer can get a lock, he either finds the data or waits (releases the lock), respectively

, . , PulseAll . :

, . , , , .

, , , - , - . , , (.. if(buf.Count == 1)) - , , , .

+2

All Articles