I am wondering how is sleep/nanosleep internally implemented? Consider this code:
{ // on a thread other than main() thread
while(1)
{
//do something
sleep(1);
}
}
would the CPU be doing constant context switching to check if sleep of 1 sec is done (i.e. an internal busy wait).
I doubt it works this way, too much inefficiency. But then how does it work?
Same question applies to nanosleep.
Note: If this is implementation/OS specific, then how can I possibly implement a more efficient scheme that doesn't lead to a constant context switching?
Exact implementation is not guaranteed here but you can expect some properties.
Usually
sleep
(3) is quite inaccurate and as Linux 'man sleep 3' states could be even implemented usingSIGALM
(signals). So it is definitely not about performance. It is definitely not about spin locks too so cannot be CPU intensive.nanosleep
is quite different animal which could be implemented even using spinlocks. Which is more important, at least in Linuxnanosleep
man is in section 2 which stands it is system call so at least it should include switch to kernel mode. Do you really need its high resolution?UPDATE
As I see your comment I do recommend
select()
usage asman select 3
states:It is proven mechanics if you need to sleep in thread for some event and this event could be linked to file descriptor.