c++ 中的 "sleep" 会发生什么?
What happens in a "sleep" in c++?
我读到它不消耗 CPU 个周期,但是调用 "sleep" 的内存中的 program/thread 发生了什么?它会被放入等待队列吗?或者会发生什么?如何将代码翻译成机器指令?或者更确切地说,它的机器指令是什么。
让我们举个例子,
`#include<WinBase.h>
main()
{
Sleep(10);
}`
此示例适用于 Windows,但我想问这个问题而不考虑平台。
答案显然是特定于操作系统和处理器的。
不知道Windows,既然是proprietary software,很多实现细节都被微软隐藏了
那么让我们考虑一个 free software 实现,例如 Linux。所以可以研究下源码
对 sleep(3) is probably executed (by your C standard library) as some system call like nanosleep(2) 的调用。
在 Linux 上,您可以使用 strace(1) 查看某些给定进程或命令执行了哪些系统调用。
任何系统调用都涉及(根据定义)操作系统 kernel. a user-mode to kernel-mode switching machine instruction gets executed (e.g. SYSENTER
on x86-64, or INT
, or some call gate, etc...). So the kernel takes control, and its scheduler is likely to run another runnable process (on its wait queue, as you guessed), or to idle the processor (if there is no runnable processes). Much later, the kernel will reschedule your process (probably after having handled many interrupts)。
如果您需要更多详细信息(对于 Linux!),请查看您的 libc 的源代码(例如 GNU libc or musl-libc) and of the kernel 本身。
当然细节很复杂,需要看很多书,研究很多源码。
你也可以读一本像Operating Systems: Three Easy Pieces这样的好教科书。它有 几个 章关于调度、进程和线程。
(我不知道Windows,但我听说它的实际系统调用集没有公布。你将针对WinAPI进行编码,并且它的具体实现方式可能是一些 MicroSoft "secret"。因此,如果您有兴趣了解 内部结构 [,我建议使用并安装 Linux - 或其他一些免费软件操作系统 - =43=]).
我读到它不消耗 CPU 个周期,但是调用 "sleep" 的内存中的 program/thread 发生了什么?它会被放入等待队列吗?或者会发生什么?如何将代码翻译成机器指令?或者更确切地说,它的机器指令是什么。
让我们举个例子,
`#include<WinBase.h>
main()
{
Sleep(10);
}`
此示例适用于 Windows,但我想问这个问题而不考虑平台。
答案显然是特定于操作系统和处理器的。 不知道Windows,既然是proprietary software,很多实现细节都被微软隐藏了
那么让我们考虑一个 free software 实现,例如 Linux。所以可以研究下源码
对 sleep(3) is probably executed (by your C standard library) as some system call like nanosleep(2) 的调用。
在 Linux 上,您可以使用 strace(1) 查看某些给定进程或命令执行了哪些系统调用。
任何系统调用都涉及(根据定义)操作系统 kernel. a user-mode to kernel-mode switching machine instruction gets executed (e.g. SYSENTER
on x86-64, or INT
, or some call gate, etc...). So the kernel takes control, and its scheduler is likely to run another runnable process (on its wait queue, as you guessed), or to idle the processor (if there is no runnable processes). Much later, the kernel will reschedule your process (probably after having handled many interrupts)。
如果您需要更多详细信息(对于 Linux!),请查看您的 libc 的源代码(例如 GNU libc or musl-libc) and of the kernel 本身。
当然细节很复杂,需要看很多书,研究很多源码。
你也可以读一本像Operating Systems: Three Easy Pieces这样的好教科书。它有 几个 章关于调度、进程和线程。
(我不知道Windows,但我听说它的实际系统调用集没有公布。你将针对WinAPI进行编码,并且它的具体实现方式可能是一些 MicroSoft "secret"。因此,如果您有兴趣了解 内部结构 [,我建议使用并安装 Linux - 或其他一些免费软件操作系统 - =43=]).