Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of sched_yield

I have few questions about the sched_yield function because I'm seeing that it is not functioning as intended in my code. Many times I see that the same thread runs again and again, even in the presence of other threads, when I try to yield it by calling sched_yield.

Also If I have multicores, will sched_yield yield for threads running on all cores, or only one core. Say for example I have Threads 1, 2 and 3 running on core 1 and Threads 4, 5 and 6 on core 2 and If sched_yield is called from Thread 2, will it be replaced by Thread 1 and 3 only, or 1, 3, 4, 5 and 6 are all possible? I am asking this because in .Net Thread.Yield only yields to threads running on the same core/processor.

like image 779
MetallicPriest Avatar asked Jun 15 '11 11:06

MetallicPriest


People also ask

What is Sched_yield?

The sched_yield() function allows a thread to give up control of a processor so that another thread can have the opportunity to run. It takes no arguments.

How does sched_ yield work?

The sched_yield() function checks to see if other threads, at the same priority as that of the calling thread, are READY to run. If so, the calling thread yields to them and places itself at the end of the READY thread queue. The sched_yield() function never yields to a lower-priority thread.


1 Answers

http://www.kernel.org/doc/man-pages/online/pages/man2/sched_yield.2.html

sched_yield() causes the calling thread to relinquish the CPU. The thread is moved to the end of the queue for its static priority and a new thread gets to run.

If the calling thread is the only thread in the highest priority list at that time, it will continue to run after a call to sched_yield().

The sched_yield is not a .Net call and the threading/process model is different to. The scheduler of Windows/.NET is not the same as scheduler of Linux. Linux even have several possible schedulers.

So, your expectations about sched_yield is wrong.

If you want to control, how threads are run, you can bind each thread to CPU. Then, threads will run only on binded CPU. If you will have several threads, binded to the same CPU, the using of sched_yield MAY switch to another thread which is binded to current CPU and is ready to run.

Also it can be bad idea to use several threads per CPU if each thread want to do a lot of CPU-intensive work.

If you want to get full control, how threads are run, you can use RealTime threads. http://www.linuxjournal.com/magazine/real-time-linux-kernel-scheduler - SCHED_FIFO and SCHED_RR RT policies.

like image 102
osgx Avatar answered Sep 28 '22 05:09

osgx