Is this code an adequate implementation of the producer/consumer pattern?
In computer science, the producer/consumer pattern is a classic example of multithreaded synchronisation. The problem describes some threads called consumers and some threads called producers sharing a common fixed-size queue.
In the above code, the queue is called _myQueue
and it's size is 1000.
Each producer job is to generate some item, put it in the queue by calling AddItem()
, and start again.
The consumers job is to remove items from the queue by calling RemoveItem()
The problem is to make sure no producer tries to add items to the queue when it's full (i.e. containing 1000 items) and no consumer tries to remove items from the queue when it's empty.
Also, we'd like to avoid situation where consumers or producers end up waiting for no reason (deadlocks).
private int _count = 1000;
private Queue<string> _myQueue = new Queue<string>();
private static object _door = new object();
public void AddItem(string someItem)
{
lock (_door)
{
while (_myQueue.Count == _count)
{
Monitor.Wait(_door);
}
_myQueue.Enqueue(someItem);
Monitor.Pulse(_door);
}
}
public string RemoveItem()
{
string item = null;
lock (_door)
{
while (_myQueue.Count == 0)
{
Monitor.Wait(_door);
}
item = _myQueue.Dequeue();
Monitor.Pulse(_door);
}
return item;
}
BlockingCollection
? Also, does it seem to work for you? \$\endgroup\$