toa*_*ven 1 c# queue multithreading producer-consumer
我开始用C#代码示例在这里.我试图调整它有几个原因:1)在我的场景中,所有任务将在消费者开始之前预先放入队列中; 2)我想将工作者抽象为一个单独的类而不是班上的原始Thread成员WorkerQueue.
我的队列似乎并没有自行处理,它只是挂起,当我在Visual Studio中打破时,它就停留在#1 _th.Join()线上WorkerThread.另外,有更好的方法来组织这个吗?暴露WaitOne()和Join()方法的东西似乎是错误的,但我想不出一个让WorkerThread队列进行交互的合适方法.
另外,如果我q.Start(#)在using块的顶部调用,则每次启动时只有一些线程(例如,线程1,2和8处理每个任务).为什么是这样?这是某种竞争条件,还是我做错了什么?
using System;
using System.Collections.Generic;
using System.Text;
using System.Messaging;
using System.Threading;
using System.Linq;
namespace QueueTest
{
class Program
{
static void Main(string[] args)
{
using (WorkQueue q = new WorkQueue())
{
q.Finished += new Action(delegate { Console.WriteLine("All jobs finished"); });
Random r = new Random();
foreach (int i in Enumerable.Range(1, 10))
q.Enqueue(r.Next(100, 500));
Console.WriteLine("All jobs queued");
q.Start(8);
}
}
}
class WorkQueue : IDisposable
{
private Queue<int> _jobs = new Queue<int>();
private int _job_count;
private EventWaitHandle _wh = new AutoResetEvent(false);
private object _lock = new object();
private List<WorkerThread> _th;
public event Action Finished;
public WorkQueue()
{
}
public void Start(int num_threads)
{
_job_count = _jobs.Count;
_th = new List<WorkerThread>(num_threads);
foreach (int i in Enumerable.Range(1, num_threads))
{
_th.Add(new WorkerThread(i, this));
_th[_th.Count - 1].JobFinished += new Action<int>(WorkQueue_JobFinished);
}
}
void WorkQueue_JobFinished(int obj)
{
lock (_lock)
{
_job_count--;
if (_job_count == 0 && Finished != null)
Finished();
}
}
public void Enqueue(int job)
{
lock (_lock)
_jobs.Enqueue(job);
_wh.Set();
}
public void Dispose()
{
Enqueue(Int32.MinValue);
_th.ForEach(th => th.Join());
_wh.Close();
}
public int GetNextJob()
{
lock (_lock)
{
if (_jobs.Count > 0)
return _jobs.Dequeue();
else
return Int32.MinValue;
}
}
public void WaitOne()
{
_wh.WaitOne();
}
}
class WorkerThread
{
private Thread _th;
private WorkQueue _q;
private int _i;
public event Action<int> JobFinished;
public WorkerThread(int i, WorkQueue q)
{
_i = i;
_q = q;
_th = new Thread(DoWork);
_th.Start();
}
public void Join()
{
_th.Join();
}
private void DoWork()
{
while (true)
{
int job = _q.GetNextJob();
if (job != Int32.MinValue)
{
Console.WriteLine("Thread {0} Got job {1}", _i, job);
Thread.Sleep(job * 10); // in reality would to actual work here
if (JobFinished != null)
JobFinished(job);
}
else
{
Console.WriteLine("Thread {0} no job available", _i);
_q.WaitOne();
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
工作线程在DoWork()中的_q.WaitOne()调用上都是阻塞的.调用线程的Join()方法将死锁,线程永远不会退出.您需要添加一个机制来向工作线程发出信号以退出.在Worker中使用WaitAny进行测试的ManualResetEvent将完成工作.
一个调试技巧:熟悉Debug + Windows + Threads窗口.它允许您在线程之间切换并查看其调用堆栈.你自己很快就找到了这个问题.