s_s
s_s

Reputation: 121

What happens in a "sleep" in c++?

I read that it does not consume CPU cycles but what happens to the program/thread in memory that called the "sleep"? Would it be put into the wait queue? Or what happens? How would the code be translated to machine instructions? Or rather what would be its machine instruction equivalent.

Lets take this example,

`#include<WinBase.h>
main()
{
    Sleep(10);
}`

This sample is for Windows, but I am meaning to ask this question irrespective of the platform.

Upvotes: 2

Views: 1408

Answers (1)

The answer is obviously operating system and processor specific. I don't know Windows, and since it is proprietary software, many implementation details are hidden by MicroSoft.

So let's consider a free software implementation like Linux. So you can study the source code.

A call to sleep(3) is probably executed (by your C standard library) as some system call like nanosleep(2).

On Linux, you can use strace(1) to see what system calls get executed by some given process or command.

Any system calls involve (by definition) the operating system 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).

If you want more details (for Linux!), look into the source code of your libc (e.g. GNU libc or musl-libc) and of the kernel itself.

Of course the details are very complex, and you'll need to read many books and study a lot of source code.

You could also read a good textbook like Operating Systems: Three Easy Pieces. It has several chapters on scheduling, processes, and threads.

(I don't know Windows, but I heard that the actual set of its system calls is not published. You'll code against the WinAPI, and how exactly it is implemented could be some MicroSoft "secret". Hence, I recommend using & installing Linux -or some other free software operating system- if you are interested in understanding the internals).

Upvotes: 2

Related Questions