I know of BlockingCollection
in .net, but this is rather for my understanding of the pattern. Is this implementation correct ?
Consumer
class Consumer
{
readonly Queue<int> _q;
public Consumer(Queue<int> q)
{
this._q = q;
}
public void Consume()
{
for (int i = 0; i < 10; i++)
{
while (_q.Count == 0)
{
}
Console.WriteLine("consuming " + _q.Dequeue());
}
}
}
Producer
class Producer
{
readonly Queue<int> _q;
readonly int _maxSize;
public Producer(Queue<int> q, int maxSize)
{
this._q = q;
this._maxSize = maxSize;
}
public void Produce()
{
for (int i = 0; i < 10; i++)
{
while (_q.Count == _maxSize)
{
}
Console.WriteLine("producing " + (i + 1));
_q.Enqueue(i + 1);
}
}
}
Client
class Program
{
static void Main(string[] args)
{
Queue<int> q = new Queue<int>();
var prod = new Producer(q, 10);
var consumer = new Consumer(q);
var producerThread = new Thread(new ThreadStart(prod.Produce));
producerThread.Start();
var consumerThread = new Thread(new ThreadStart(consumer.Consume));
consumerThread.Start();
}
}
The way I see it, this handles the race condition in Inadequate implementation by introducing while
instead of if
The program runs fine on my machine, so is this correct or am i missing something? why the need for synchronization?