我是新手,正在学习线程的不同概念。
现在我正在使用计时器线程进行生产者/消费者模式。问题是,在让计时器线程滴答一定时间并处置所有创建的生产者和消费者线程之前,我不知道如何检查所有生产者和消费者线程是否完成其进程。
想请您帮助和指导我如何为此方法创建一个解决方案。
这是我的示例代码:
public class WorkerThread
{
public BlockingQueue<Item> collection = new BlockingQueue<Item>(100);
private Timer TimerThread { get; set; }
public void ThreadTimer()
{
this.TimerThread = new Timer(new TimerCallback(StartMonitor), null, 500, Timeout.Infinite);
}
public void StartMonitor(object state)
{
List<Thread> producers = new List<Thread>();
List<Thread> consumers = new List<Thread>();
for (int i = 0; i < 1; i++)
{
producers.Add(new Thread(() => RunProducers(this.collection)));
}
//TODO: Start all producer threads...
for (int i = 0; i < 2; i++)
{
consumers.Add(new Thread(() => RunConsumers(this.collection)));
}
//TODO: Start all consumer threads...
//TODO: Let Thread wait until all worker threads are done
//TODO: Dispose Threads
TimerThread.Change(5000, Timeout.Infinite);
}
public void RunProducers(BlockingQueue<Item> collection)
{
List<Item> lsItems = CreateListOfItems();
foreach(var item in lsItems)
{
collection.Add(item);
}
}
public void RunConsumers(BlockingQueue<Item> collection)
{
while(true)
{
Item item = collection.Take();
Console.WriteLine("Processed[{0}] : {1}", item.ID, item.Name);
//Thread.Sleep(100);
}
}
public List<Item> CreateListOfItems()
{
List<Item> lsItems = new List<Item>();
for (int i = 0; i <= 9999; i++)
{
lsItems.Add(new Item() { ID = i, Name = "Item[" + i + "]" });
}
return lsItems;
}
}
块集合实现(由于我们的环境在.Net 3.5中,因此我们无法使用更高版本的库)。
public class BlockingQueue<T>
{
private readonly Queue<T> queue = new Queue<T>();
private readonly int MaxSize;
public bool closing;
public BlockingQueue(int maxSize) {
this.MaxSize = maxSize;
}
public void Add(T item)
{
lock(queue)
{
while(queue.Count >= this.MaxSize)
{
Monitor.Wait(queue);
}
queue.Enqueue(item);
if(queue.Count == 1)
{
Monitor.PulseAll(queue);
}
}
}
public T Take()
{
lock(queue)
{
while(queue.Count == 0)
{
Monitor.Wait(queue);
}
T item = queue.Dequeue();
if(queue.Count == MaxSize - 1)
{
Monitor.PulseAll(queue);
}
return item;
}
}
public void Close()
{
lock (queue)
{
closing = true;
Monitor.PulseAll(queue);
}
}
public bool TryDequeue(out T value)
{
lock (queue)
{
while (queue.Count == 0)
{
if (closing)
{
value = default(T);
return false;
}
Monitor.Wait(queue);
}
value = queue.Dequeue();
if (queue.Count == MaxSize - 1)
{
Monitor.PulseAll(queue);
}
return true;
}
}
}