我有一個簡單的單生產者/雙消費者代碼,如下所示,但輸出顯示只有C2
消耗。我的代碼中是否有錯誤?C#生產者/消費者模式
class Program
{
static void Main(string[] args)
{
Object lockObj = new object();
Queue<string> queue = new Queue<string>();
Producer p = new Producer(queue, lockObj);
Consumer c1 = new Consumer(queue, lockObj, "c1");
Consumer c2 = new Consumer(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 Consumer
{
Queue<string> queue;
Object lockObject;
string name;
public Consumer(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} Consuming {1}", name, item);
}
}
}
}
輸出是:
Producing item1
c2 Consuming item1
Producing item2
c2 Consuming item2
Producing item3
c2 Consuming item3
Producing item4
c2 Consuming item4
Producing item5
c2 Consuming item5
Producing item6
c2 Consuming item6
Producing item7
c2 Consuming item7
Producing item8
c2 Consuming item8
Producing item9
c2 Consuming item9
Producing item10
c2 Consuming item10
Producing item11
c2 Consuming item11
Producing item12
c2 Consuming item12
Producing item13
c2 Consuming item13
Producing item14
c2 Consuming item14
Producing item15
c2 Consuming item15
你能描述一下你究竟想達到什麼嗎?你的例子看起來有點人爲,所以我不能從上下文中確定你需要做什麼。 – jrista 2009-09-03 03:10:55
嗨南南,請看看[這個生產者消費者的例子](https://stackoverflow.com/questions/733793/implementing-the-producer-consumer-pattern-in-c-sharp/47179576#47179576),它可能會幫助你。 – 2017-11-08 12:58:50