如果我Thread.Sleep()真的很忙吗? [英] Is it Really Busy Waiting If I Thread.Sleep()?

查看:1688
本文介绍了如果我Thread.Sleep()真的很忙吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题在定义上有些挑剔:

My question is a bit nit-picky on definitions:

下面的代码可以描述为忙等待"吗?尽管它使用Thread.Sleep()进行上下文切换?

Can the code below be described as "busy waiting"? Despite the fact that it uses Thread.Sleep() to allow for context switching?

while (true) {
    if (work_is_ready){
        doWork();
    }
    Thread.Sleep(A_FEW_MILLISECONDS);
}

PS-Wikipedia中对繁忙等待的当前定义表明,这是一种较少浪费"的繁忙等待形式.

PS - The current definition for busy waiting in Wikipedia suggests that it is a "less wasteful" form of busy waiting.

推荐答案

任何轮询循环(无论轮询操作之间的时间间隔如何)都是繁忙的等待.当然,睡眠几毫秒比根本不睡眠要少忙"得多,但是它仍然涉及处理:线程上下文切换和一些最少的条件检查.

Any polling loop, regardless of the time between polling operations, is a busy wait. Granted, sleeping a few milliseconds is a lot less "busy" than no sleep at all, but it still involves processing: thread context switches and some minimal condition checking.

不忙等待是阻塞呼叫.您的示例的忙碌版本将涉及等待同步原语,例如事件或条件变量.例如,此伪代码:

A non-busy wait is a blocking call. The non-busy version of your example would involve waiting on a synchronization primitive such as an event or a condition variable. For example, this pseudocode:

// initialize an event to be set when work is ready
Event word_is_ready;
work_is_ready.Reset();

// in code that processes work items
while (true)
{
    work_is_ready.Wait();  // non-busy wait for work item
    do_work();
}

这里的区别是没有定期轮询. Wait调用会阻塞,并且直到事件被设置之前,线程才永远不会被调度.

The difference here is that there is no periodic polling. The Wait call blocks and the thread is never scheduled until the event is set.

这篇关于如果我Thread.Sleep()真的很忙吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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