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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With