Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does nanosleep 0 still execute?

Tags:

c

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?

like image 696
ColeSlaw Avatar asked Jun 07 '26 03:06

ColeSlaw


1 Answers

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.

like image 55
doron Avatar answered Jun 10 '26 18:06

doron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!