←back to thread

115 points saisrirampur | 4 comments | | HN request time: 0.832s | source
Show context
gsliepen ◴[] No.44568872[source]

  pg_usleep(1000L);
Virtually any time you put a fixed sleep in your program, it's going to be wrong. It is either too long or too short, and even if it is perfect, there is no guarantee your program will actually sleep for exactly the requested amount of time. A condition variable or something similar would be the right thing to use here.

Of course, if this code path really is only taken very infrequently, you can get away with it. But assumptions are not always right, it's better to make the code robust in all cases.

replies(4): >>44569067 #>>44570238 #>>44571006 #>>44571476 #
delusional ◴[] No.44569067[source]
> there is no guarantee your program will actually sleep for exactly the requested amount of time

This is technically true, but in the same way that under a preemptive operating system there's no guarantee that you'll ever be scheduled. The sleep is a minimum time you will sleep for, beyond that you already have no guarantee about when the next instruction executes.

replies(1): >>44569435 #
1. dwattttt ◴[] No.44569435[source]
Spurious wakeups enters the chat.
replies(1): >>44569882 #
2. quietbritishjim ◴[] No.44569882[source]
Any reasonable sleep API will handle spurious wake ups under the hood and not return control.
replies(1): >>44569909 #
3. Joker_vD ◴[] No.44569909[source]
It will also ignore those pesky signals and restart the sleep :)

On a more serious note, any reasonable sleep API should either report all wake ups, no matter the reason, or none except for the timeout expiration itself. Any additional "reasonable" filtering is a loaded footgun because different API users have different ideas of what is "reasonable" for them.

replies(1): >>44570473 #
4. ◴[] No.44570473{3}[source]