AMSA

Week 3: Scheduling and nice

Ferran Aran Domingo
Oriol Agost Batalla
Pablo Fraile Alonso

Goals for today

  • Any questions from the previous session?
  • Learn what an scheduler is and why we need it
  • Learn what priority is
  • Learn how we can alter this priority with nice
  • Present and explain Prac-2.2

Scheduler

How does it identify these tasks?

  • Linux doesn’t differenciate between processes and threads, in fact, it has a struct (task_struct) that is a Kernel descriptor for both threads and processes (tasks).

Note

In fact, this struct ID is just the PID if it’s a process, and the TGID if it’s a thred (or kernel thread), but he doesn’t care. It’s the same for him

  • Threads are just tasks sharing resources.

  • We need a scheduler because we want to run things concurrently, and run more tasks than cores.

What are priorities? What do they have to do with scheduling?

How do we decide which tasks get CPU time (go into the bar)?

With priority, a number tied to each task

  • Range: -20 (highest priority, most CPU time) to +19 (lowest priority, smallest CPU time)
  • Default: 0
  • Only for normal (non-real-time) processes
  • Only for certain scheduling algorithms
  • Can be changed

How can we change the priority? The nice command

When a program is nice, it leaves more time for the other programs, leaving more room to other ones. By using nice, this is exactly what we do, make it “nicer” and alter it’s priority. In fact, the nice program code is really simple:

//...
  ok = (setpriority (PRIO_PROCESS, 0, current_niceness + adjustment) == 0); // Syscall to setpriority
//...
  execvp (argv[i], &argv[i]);
//...

Note

  • Modifying the priority by making it less nice makes it mandatory to run the command with sudo
  • Sudo is not needed the other way round

Internal priority and nice priority

Internally, the priority is actually interpreted different, hence the system uses helper functions to translate between these two types of priorities.

static inline long nice_to_rlimit(long nice)
{
    return (MAX_NICE - nice + 1);
}

/*
 * Convert rlimit style value [1,40] to nice value [-20, 19].
 */
static inline long rlimit_to_nice(long prio)
{
    return (MAX_NICE - prio + 1);
}

See more on the linux kernel sched code

Quizz

Nice & Priority questions

  • Why do we need sudo to lower nice?
  • Which priority uses our system internally to keep track of priority?

References

Additional Exercices

If you really want to understand a little bit more what happens under the hood, you can do the following exercices. Be aware that you should read the “References” first, and then try to do this exercises.

  • Implement your own “nice” with Python. Assume all parameters will be correct, it should execute via:
$ python3 my_nice.py <name_of_the_program_you_want_to_be_nice> <nice_value>

Activity 2.2

Ready to have some fun? Check out the second part of the second AMSA activity here!