I have simple one producer two consumers code as follow but the output are only C2 consuming. any bug in my code?
class Program
{
static void Main(string[] args)
{
Object lockObj = new object();
Queue<string> queue = new Queue<string>();
Producer p = new Producer(queue, lockObj);
Comsumer c1 = new Comsumer(queue, lockObj, "c1");
Comsumer c2 = new Comsumer(queue, lockObj, "c2");
Thread t1 = new Thread(c1.consume);
Thread t2 = new Thread(c2.consume);
t1.Start();
t2.Start();
Thread t = new Thread(p.produce);
t.Start();
Console.ReadLine();
}
}
public class Producer
{
Queue<string> queue;
Object lockObject;
static int seq = 0;
public Producer(Queue<string> queue, Object lockObject)
{
this.queue = queue;
this.lockObject = lockObject;
}
public void produce()
{
while( seq++ <15) //just testinng 15 items
{
lock (lockObject)
{
string item = "item" + seq;
queue.Enqueue(item);
Console.WriteLine("Producing {0}", item);
if (queue.Count == 1)
{ // first
Monitor.PulseAll(lockObject);
}
}
}
}
}
public class Comsumer
{
Queue<string> queue;
Object lockObject;
string name;
public Comsumer(Queue<string> queue, Object lockObject, string name)
{
this.queue = queue;
this.lockObject = lockObject;
this.name = name;
}
public void consume()
{
string item;
while (true)
{
lock (lockObject)
{
if (queue.Count == 0)
{
Monitor.Wait(lockObject);
continue;
}
item = queue.Dequeue();
Console.WriteLine(" {0} Comsuming {1}", name, item);
}
}
}
}
and output is
Producing item1 c2 Comsuming item1
Producing item2 c2 Comsuming item2
Producing item3 c2 Comsuming item3
Producing item4 c2 Comsuming item4
Producing item5 c2 Comsuming item5
Producing item6 c2 Comsuming item6
Producing item7 c2 Comsuming item7
Producing item8 c2 Comsuming item8
Producing item9 c2 Comsuming item9
Producing item10 c2 Comsuming item10
Producing item11 c2 Comsuming item11
Producing item12 c2 Comsuming item12
Producing item13 c2 Comsuming item13
Producing item14 c2 Comsuming item14
Producing item15 c2 Comsuming item15