I'm currently learning pthreads and am struggling to understand the relationship between thread priority and policy. What I know so far:
The thread priority is an integer that indicates priority. The higher this number, the higher priority the thread is treated by the OS.
The thread policy determines how the thread is executed among processes with the shared priority number. SCHED_RR and SCHED_FIFO are real-time policies that continuously execute unless an explicit "sleep" command is issued. Thus a programmer must very carefully write code when using these policies. SCHED_OTHER is a round robin policy that is not executed in real-time.
However, let's say I have the following scenarios (assume each thread does not use a "sleep" command).
Thread 1: priority = 0, policy = SCHED_OTHER
Thread 2: priority = 1, policy = SCHED_OTHER
// would thread 1 run at all?
Thread 1: priority = 0, policy = SCHED_RR
Thread 2: priority = 1, policy = SCHED_RR
// would thread 1 run at all?
I'm confused as to whether or not the the thread policy affects the thread priority, or if the thread priority always trumps the policy.
Edit: Found a web page that cleared up most of my confusion: https://computing.llnl.gov/tutorials/pthreads/man/sched_setscheduler.txt
Documentation for SCHED_RR
says that it is the same as SCHED_FIFO
except in certain cases when two or more threads have the same static priority.
Documentation for SCHED_FIFO
makes it clear that if a thread with higher static priority is ready-to-run but not running, and if one or more threads with lower static priority are running, then one of the lower priority threads will be preempted in favor of the higher priority thread.
would thread 1 run at all [in the SCHED_RR case]?
That depends. What is thread 0 doing? How many CPUs does the system have? If those were the only two threads on a system that had only one CPU, then thread 1 would be allowed to run whenever thread 0 did not want to run.
Generally speaking, when you use static priorities, you want the highest priority threads to do the least amount of work. A high priority thread should spend most of its time waiting for some event. Then when the event happens, the thread should promptly acknowledge it, and then possibly signal a lower-priority thread if some kind of follow-up computation is required.
would thread 1 run at all [in the SCHED_OTHER case]?
As mentioned in my comment, if you're talking about static priorities (i.e., as set by the sched_setattr()
system call, then the question is meaningless because threads that are scheduled under the SCHED_OTHER policy are all required to have the same static priority--zero.