sleep()如何工作? [英] How does sleep() work?

查看:104
本文介绍了sleep()如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个愚蠢的问题,但是sleep()wait()pause()函数如何工作?

This might be a stupid question, but how do sleep(), wait(), pause(), functions work?

推荐答案

我们可以从更抽象的角度看待睡眠操作:它是让您等待事件的操作.
sleep调用经过的时间超过sleep参数时,将触发相关事件.

We can see the sleeping operation from a more abstract point of view: it is an operation that let you wait for an event.
The event in question is triggered when the time passed from sleep invocation exceeds the sleep parameter.

当一个进程处于活动状态(即,它拥有一个CPU)时,它可以以活动或被动方式等待事件:

When a process is active (ie: it owns a CPU) it can wait for an event in an active or in a passive way:

  • 活动等待是指某个进程主动/明确地等待事件的时间:

  • An active wait is when a process actively/explicitly waits for the event:

sleep( t ):
    while not [event: elapsedTime > t ]:
        NOP // no operatior - do nothing

这是一个微不足道的算法,可以在任何地方以可移植的方式实现,但是存在一个问题,即您的进程正在积极等待时,它仍然拥有CPU,浪费了它(因为您的进程实际上并不需要CPU,而其他任务可能需要它.)

This is a trivial algorithm and can be implemented wherever in a portable way, but has the issue that while your process is actively waiting it still owns the CPU, wasting it (since your process doesn't really need the CPU, while other tasks could need it).

通常,这只能由那些不能被动等待的进程来完成(请参见下面的要点).

Usually this should be done only by those process that cannot passively wait (see the point below).

通过在事件发生时询问其他事项来唤醒您,然后暂停自身(即释放CPU)来完成被动等待:

A passive wait instead is done by asking to something else to wake you up when the event happens, and suspending yourself (ie: releasing the CPU):

sleep( t ):
    system.wakeMeUpWhen( [event: elapsedTime > t ] )
    release CPU

要实现被动等待,您需要一些外部支持:事件发生时,您必须能够释放CPU并要求其他人将您唤醒.

In order to implement a passive wait you need some external support: you must be able to release your CPU and to ask somebody else to wake you up when the event happens.

除非硬件提供wakeMeUpWhen操作,否则在单任务设备(如许多嵌入式设备)上这是不可能的,因为没有人释放CPU或要求唤醒它.

This could be not possible on single-task devices (like many embedded devices) unless the hardware provides a wakeMeUpWhen operation, since there's nobody to release the CPU to or to ask to been waken up.

x86处理器(和大多数其他处理器)提供了 HLT 操作,该操作可使CPU休眠直到出现外部中断被触发.这样,操作系统内核也可以休眠以保持CPU凉爽.

x86 processors (and most others) offer a HLT operation that lets the CPU sleep until an external interrupt is triggered. This way also operating system kernels can sleep in order to keep the CPU cool.

这篇关于sleep()如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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