创建匿名线程? [英] Creating Anonymous Threads?

查看:91
本文介绍了创建匿名线程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要知道这个想法是否可行并且可行:我正在使用多线程生产者使用者队列设计模式.队列的建立速度太快,无法让我的线程有足够的时间及时处理数据,因此,如果队列达到一定大小,我将尝试动态创建线程.检出我试图实现的代码,让我看看它是否合乎逻辑:

Need to know if this idea makes sense and is doable: I''m using multi-threaded producer consumer queue design pattern. The building of the queue is too fast and not allowing my thread enough time to process the data in a timely fashion so I''m trying to create threads dynamically if the queue reaches a certain size. Checkout this code I''m trying to implement and let me if it''s logical and doable:

const int MAX_QUEUE = 1000;

Queue<string> que = new Queue<string>();
EventWaitHandle ewh =  new AutoResetEvent(false);
object sync = new object();
MyWorker  myWorker = new MyWorker(sync,ewh,que);
Thread thrd = new Thread(myWorker.Work);
thrd.Start();


private void producer(string task)
{
  lock(sync)
  {
    que.Enqueue(task);
    
    // I''m trying to create multiple threads dynamically to assist int processing the queue vs only
    // using the one thread that I instantiated...
    if(que.Count > MAX_QUEUE)
    { 
      new Thread(delegate(){ new MyWorker(que,sync,ewh).Work();}).Start();
    }
  }
  ewh.Set();
}

class MyWorker
{
  object sync;
  EventWaitHandle ewh;
  Queue<string> que;

  public MyWorker(object sync, EventWaitHandle ewh, Queue<string> que)
  {
     this.sync = sync;
     this.ewh = ewh;
     this.que = que;
   }

   public void Work()
   {
      while(true)
      {
         string task = "";
         lock(sync)
         {
           if(que.Count > 0)
           {
             task = que.Dequeue();
           }
         }
         
           if(task != "")
           {
             // process task...
           }
           else
             ewh.WaitOne();
       }
   }
}</string></string></string></string></pre>
[edit]Code Block added - OriginalGriff[/edit]
[edit2]Spurious string tags removed - OriginalGriff[/edit2]</string></string></string></string>

推荐答案

我看到了一些问题.首先,我看不到线程如何结束,它们将永远陷入while(true)循环中.可能缺少一些代码,但是您需要确保可以退出该循环以允许线程正确退出.

其次,如果您添加的线程多于处理器上的内核,那么您将不会获得任何性能提升,因为有些线程将在运行,而另一些线​​程将在处理器上等待它们的时间.它实际上可能会减慢您的速度.

因此,您可能想做的就是在启动后立即创建固定数量的线程(您应该能够使用Environment.ProcessorCount获取可以并行运行的线程数量),然后如果队列开始变满您只需要停止向其中添加项目,直到有足够的空间即可.

忘记提及了,如果您要动态创建大量线程,您可能还想研究使用线程池
I see a few problems. First I can''t see how the threads can ever end, they''ll be stuck in that while(true) loop forever. There maybe some code missing but you need to make sure you can break out of that loop to allow the thread to exit properly.

Secondly, if you add more threads than there are cores on a processor then you won''t gain any performance increase because while some threads will be running others will be waiting for their time on the processor. It could actually slow you down.

So what you may want to do is create a fixed number of threads as soon as you start (you should be able to use Environment.ProcessorCount to get the number of threads that can run in parallel) and then if your queue starts to get full you will simply have to stop adding items to it until there is enough room.

Forgot to mention, you may also want to look into using a Thread Pool if your going to be creating lots of threads on the fly http://msdn.microsoft.com/en-us/library/3dasc8as(v=vs.80).aspx[^]


MyWorker worker = new MyWorker();

private void producer(string Task)
{
    Thread taskthread = new Thread(new ParameterizedThreadStart(worker.Work));
    taskthread.Start(Task);
}

class MyWorker
{
    public MyWorker()
    {
    }

    public void Work(object objTask)
    {
        string Task = (string)objTask;

        if (Task != "")
        {
            // process task...
        }
    }
}



这样,您就可以让Windows为您进行提示了,您仍然可以在线程中使用MyWorker类的commen变量.



In this way you will let windows do the cue-ing for you, and you still can use the commen variables of the MyWorker class in your thread.


此问题已在我的Tips/中解决.技巧文章:用于线程通信和线程间调用的简单阻塞队列 [ ^ ].

—SA
This problem is solved in my Tips/Tricks article: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^].

—SA


这篇关于创建匿名线程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆