# Priorities

What if the bathroom is currently locked and a number of people are waiting to use it? Obviously, all the people are sitting around outside, waiting for whoever is in the bathroom to get out. The real question is, What happens when the door unlocks? Who gets to go next?

You'd figure that it would be "fair" to allow whoever is waiting the longest to go next. Or it might be "fair" to let whoever is the oldest go next. Or tallest. Or most important. There are any number of ways to determine what's "fair."

We solve this with threads via two factors: priority and length of wait.

Suppose two people show up at the (locked) bathroom door at the same time. One of them has a pressing deadline (they're already late for a meeting) whereas the other doesn't. Wouldn't it make sense to allow the person with the pressing deadline to go next? Well, of course it would. The only question is how you decide who's more "important." This can be done by assigning a priority (let's just use a number like QNX Neutrino doesâ€”one is the lowest usable priority, and 255 is the highest as of this version). The people in the house that have pressing deadlines would be given a higher priority, and those that don't would be given a lower priority.

Same thing with threads. A thread inherits its scheduling policy from its parent thread, but can (if it has the authority to do so) call pthread_setschedparam() to change its scheduling policy and priority, or pthread_setschedprio() to change just its priority.

If a number of threads are waiting, and the mutex becomes unlocked, we would give the mutex to the waiting thread with the highest priority. Suppose, however, that both people have the same priority. Now what do you do? Well, in that case, it would be "fair" to allow the person who's been waiting the longest to go next. This is not only "fair," but it's also what the microkernel does. In the case of a bunch of threads waiting, we go primarily by priority, and secondarily by length of wait.

The mutex is certainly not the only synchronization object that we'll encounter. Let's look at some others.