Linux time: sleep and wakeup
Wait without keeping the processor busy
Sometimes a program has to wait for a timer or another event. While it is asleep, it is not ready to use the processor, so Linux can give that time to other work. A busy loop does the opposite: it keeps checking a condition and uses CPU while it waits. For a short, simple delay, a shell command can sleep:
time sleep 2
The shell command sleep 2 asks Linux to pause it for about two seconds. The shell's time output shows elapsed wall time and CPU time. The command should use very little CPU, while elapsed time can be slightly longer than two seconds because waking up does not guarantee immediate execution.
Timer expiry is not a scheduled start
Programs can request a delay with nanosleep() or clock_nanosleep(). The kernel sets a timer and makes the sleeping thread eligible to run when the requested interval expires. Eligible means ready to compete for CPU; another task may still be running, or the CPU may be busy. Timer resolution and system load can add delay. A sleep is not a deadline guarantee, and a signal can interrupt some sleep calls before the interval completes.
Sleep can also mean waiting for an event rather than time. A process may block while reading a pipe, waiting for a child process, or waiting for a synchronization event. The kernel makes it runnable when the relevant event occurs. Event-driven waits usually use less CPU than repeatedly polling in a tight loop.
A thread waiting on a condition variable or mutex can sleep until another thread signals the condition or releases the lock. When it wakes, it must check the condition again: another thread may change it before the awakened thread runs. A notification means “check now,” not that the condition is guaranteed to be true.
Choose the right clock
A signal can interrupt a sleep system call. nanosleep() can report the time remaining; clock_nanosleep() lets a program choose a clock and wait for an absolute deadline. Absolute deadlines help with periodic work because repeating a relative sleep after each task can accumulate timing drift.
For elapsed-time waits, use a monotonic clock where available. It moves forward without following changes to the calendar clock. A realtime clock can be adjusted, changing its date and time. Linux also provides clocks with different suspend behavior; choose one according to whether time spent suspended should count.




