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

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

问题描述

这可能是一个愚蠢的问题,但是 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.

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

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