为什么在生产者使用者队列中使用While循环? [英] Why is While Loop in the Producer Consumer Queue?
问题描述
大家好,
我不完全了解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
推荐答案
请参阅我的提示/技巧"文章中的完整源代码和解释: ^ ].它使用泛型仅以一种有文化的方式解决了完全相同的问题.
您非常与线程混淆,而不仅仅是WaitOne
.当线程正在调用诸如WaitOne
之类的阻塞代码时,它正在使用零CPU时间休眠".只是简单地关闭线程,并且从不计划再次执行线程,直到线程被唤醒".同一实例的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 justWaitOne
. When a thread is calling a blocking code such asWaitOne
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屋!