ColeSlaw
ColeSlaw

Reputation: 29

why does nanosleep 0 still execute?

Im trying to test the performance of nanosleep in my code. When I call nanosleep and pass in 0 seconds and 0 nanoseconds I get a different value compared to not even calling nanosleep. Shouldn't nanosleep have no effect at all if I call it with 0 as argument?

Upvotes: 2

Views: 533

Answers (2)

doron
doron

Reputation: 28892

sleep(0) and probably nanosleep with zero provide a mechanism for a thread to surrender the rest of its timeslice. This effectively is a thread yield. So when calling sleep(0) we enter kernel mode and places the thread onto the "runnable" queue. The thread then is scheduled to resume when the next available timeslot comes available. When this happens is left entirely up to the operating system.

One usecase (maybe not the best usecase) for this is a userspace spinlock. When "spinning while waiting for a resource, we call sleep(0). This allows the task that may release the resource to be scheduled allowing the lock to be released quicker.

Upvotes: 6

klutt
klutt

Reputation: 31389

If you don't want a function to run, don't call it.

Functions have overheads. They need to initialize a stackframe, jump to the functions code, do the work and then jump back. It's only the "do the work" that can be altered.

You can of course inline the function to skip the jumps and stack frame setup, but you will always need to check the value of the argument. Even such a simple thing as if(x==0) takes time when it comes to the nanoscale.

The problem here is almost more philosophical than technical. A function cannot by itself determine if it should be run or not, because it needs to be run to do anything that all, including determining if it should be run or not.

Upvotes: 4

Related Questions