如何在操作系统级别实现睡眠? [英] How is sleep implemented at the OS level?

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

问题描述

我只是很感兴趣sleep(time in ms)是如何在C库中实现的,或者基本上是在OS级别上实现的...

我正在猜测...

  1. 可能是基于您对nop进行一会儿循环的处理器速度的基础(我不确定睡眠时间是否准确)...
  2. 处理器中的任何特殊寄存器,您在其中写入一些值,然后处理器仅在指定时间停止(这将非常低效,因为处理器甚至无法运行其他程序).

有任何线索吗?大概C库的源代码可以解释吗?我不太在意"C"如何实现它……我只是想知道总体上"sleep()"函数是如何实现的.

解决方案

Sleep()在操作系统级别实现.当任务/线程/进程处于休眠状态时,处理器不会旋转.将该特定线程放在待处理队列中(该线程尚未准备好运行),直到时间到期为止,届时该线程将被放置在准备运行队列中.

同时,将运行其他准备运行的线程.

只有没有准备好运行的线程时,操作系统才会进入空闲线程,该线程通常会发出指令以关闭处理器(或者无论如何都进入低功耗状态),直到发生硬件中断为止.

仅对于非常简单的系统(例如最简单的嵌入式系统),Sleep()可能实际上只是忙碌的等待循环而实现.

任何操作系统教科书,例如 Tanenbaum撰写的现代操作系统" 将对此进行详细介绍-几乎涵盖其中的任何一个(甚至是旧的,便宜的,二手的).

I am just interested how sleep(time in ms) is implemented in a C library or basically at the OS level...

I am guessing...

  1. May be the based on the processor speed you do a while loop of nop's (I am not sure if the sleep time will be accurate)...
  2. Any special register in processor, where you write some value and the processor simply halts for specified time (this would be very inefficient as the processor can't run even other programs).

Any clues? Probably C library source code can explain? I am not too particular about how "C" is implementing it... I am just wondering in general how the "sleep()" function is implemented.

解决方案

Sleep() is implemented at the OS level. The processor doesn't spin when a task/thread/process is sleeping. That particular thread is put on a pending queue (the thread isn't ready to run) until the time has expired at which point the thread will be placed on the ready to run queue.

In the meantime, other threads that are ready to run will be run.

Only if no threads are ready to run will the OS go into the idle thread, which in generally issues instructions to shutdown (or put into a low-power state anyway) the processor until an hardware interrupt occurs.

Only for a very simple system (like the most simple of embedded systems), might Sleep() actually be implemented as nothing more than a busy wait loop.

Any operating system textbook, such as "Modern Operating Systems" by Tanenbaum will cover this in great detail - pretty much any of them (even an old, cheap, used one).

这篇关于如何在操作系统级别实现睡眠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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