3 ms·
Why is calling sched_yield() a mistake? What's the correct way to yield CPU without calling sleep?
by sillysaurusx 7y ago
Why is calling sched_yield() a mistake? What's the correct way to yield CPU without calling sleep?
- colonwqbang 7y agoIt's explained in the linked post. Why don't you want to call sleep?
- gpderetta 7y agoBeacuse it would act as as an even worse sched yield.
- temac 7y agoNot in every cases, but both are certainly suboptimal compared to a diretected wake up.
- deleted 7y ago[deleted]
- mritun 7y agoCalling sleep(1) instead of thread yield is faster - see the twitter thread for a proof.
- de_watcher 7y agoStill worse: it's a confusing code, and it's also confusing that it's faster.
- colonwqbang 7y agoI guess I can't really see the use case here. If you want to sleep, it's usually because you're waiting for something: file descriptor, semaphore/mutex, or a certain amount of time to pass. If none of these conditions apply, can't you just continue to run and let the scheduler do its work? (maybe with an appropriate nice setting if you are doing "less important" work). The scheduler itself uses fixed time interrupts for its basic functions, so "sleep(fixed_time_interval)" is what you will get in the end anyway on a preemptive system.
- gpderetta 7y agoFutex wait, or any other blocking syscall.
- dante_dev 7y agoyou may want to read Linus's answer about it https://www.realworldtech.com/forum/?threadid=189711&curpostid=189752 https://www.realworldtech.com/forum/?threadid=189711&curpost...
- atq2119 7y agoYou really should just read the linked article, but the tl;dr is that sched_yield() does not convey intent (except in narrow realtime scenarios that you should not be using in the first place). Tell the kernel why you want to yield CPU. Work with the kernel, not against it. Do you want to yield because you genuinely want to wait until some future point in time? Use sleep. Is it because you're waiting for some I/O? Use poll or its variants. Is it because you're waiting for a signal from another thread? Use mutexes, condition variables, etc. that call futex under the hood.
- mannykannot 7y agoIf a thread can do no more for the moment, then either it is finished, or it is waiting for something to happen. In the latter case, the best thing is to be woken on that event, and the next best is to poll for it. Sleep is only the best solution when that event is literally the passage of time.
- pizlonator 7y agosched_yield means “yield to any thread if it’s easy to do so or do nothing”. That meaning fits the requirements of some algorithms, particularly if you call it a finite number of times before doing something more drastic like a blocking syscall (like futex wait, lock acquisition, whatever) that will block until the condition you’re waiting for is fulfilled. Think of it as a speculative optimization on top of busy waiting, not as a way to control the scheduler.