为什么在生产者使用者队列中使用While循环? [英] Why is While Loop in the Producer Consumer Queue?

查看:72
本文介绍了为什么在生产者使用者队列中使用While循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,

我不完全了解EventWaitHandle类和生产者使用者队列中的while():

Hi everyone,

I''m not fully understanding the EventWaitHandle class and the while() within the producer consumer queue:

Queue<string> que = new Queue<string>();
EventWaitHandle wh = new AutoResetEvent(false);
object sync = new object();

private void job(string task)
{
  lock(sync)
  {
    queue.Enqueue(task);
  }
  wh.Set();
}

private void worker()
{
  while(true)
  {
     string copyTask = "";

     lock(sync)
     {
       if(queue.Count > 0)
       {
         copyTask = queue.Dequeue();
       }
       
      if(copyTask != "")
      {
          // process data...
      }
      else
        wh.WaitOne();
  }
}
</string></string>


我的问题是:如果" wh.WaitOne()wh.Set()发送一个信号,通知job()准备处理数据,为什么while()是必需的? wh.WaitOne()是否停止while()循环并使其进入睡眠状态?还是让worker()运行的线程进入睡眠状态?

我已经阅读并完成了一些有关此的教程,但我仍然不清楚自己在做什么.有人可以告诉我这里发生了什么吗?

预先感谢!
-Donald


My question is: "if" the wh.WaitOne() sends a signal to wh.Set() notifying job() that it''s ready to process data why is the while() necessary? Does the wh.WaitOne() stop the while() loop and put it to sleep? Or does it put the Thread that worker() is running on to sleep?

I''ve read and done a few tutorials on this and I''m still not clearly understanding what''s going on. Can someone please explain to me what''s happening here?

Thank in advance!
-Donald

推荐答案

请参阅我的提示/技巧"文章中的完整源代码和解释:EventWaitHandle.Set会使处于等待状态的线程唤醒.根本没有循环.您可能会想到的就是所谓的自旋等待",这绝对是邪恶的.

—SA
See the full source code and explanation in my Tips/Tricks article: Simple Blocking Queue for Thread Communication and Inter-thread Invocation[^]. It solves exactly the same problem, only in a cultured way, using generics.

You''re very confused with threading, not just WaitOne. When a thread is calling a blocking code such as WaitOne it is "sleeping" using zero CPU time. The thread simply switched of and never scheduled for execution again until it is "waken up". EventWaitHandle.Set of the same instance makes the thread in wait state wake up. There is no loop at all. That you probably have in mind is called "spin-wait" and is the absolute evil.

—SA


这篇关于为什么在生产者使用者队列中使用While循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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