Can't provoke Priority Inversion in C++

ぐ巨炮叔叔 提交于 2019-12-03 17:34:43
  1. Are you running the program as root?

  2. What are your values of these sysctl parameters? Here are mine from an Ubuntu box. The default is to give real time only 0.95 seconds out of a 1 second slice:

    kernel.sched_rt_period_us = 1000000
    kernel.sched_rt_runtime_us = 950000
    

    This prevents the real-time domain from taking all the CPU. If you want real real time, you have to disable these parameters.

See: http://www.kernel.org/doc/Documentation/scheduler/sched-rt-group.txt

If you set sched_rt_runtime_us to -1, you disable this safety mechanism.

Re: I'm trying to provoke Priority Inversion on a small C++ program for demonstration purposes but I can't: The low priority thread that holds the mutex is not preempted and keeps running ...

That is the beginning of a priority inversion scenario. A low-priority thread grabs an exclusive resource (e.g. mutex) on which high priority threads then block.

To properly show the consequences of priority inversion, you require, for example, three threads: a low (L), middle (M) and high (H) priority thread.

L locks a mutex, for which H contends. So L is running, H is not. This is bad already: important thread H is waiting for less important thread L to do something.

Now M becomes runnable and is compute-intensive. M doesn't care about the mutex; it is not related to H or L. But M has a higher priority than L and kicks L off the CPU.

So now M continues to execute, preventing L from running. That prevents L from reaching the line of code where it releases the mutex, and that prevents H from getting the mutex.

So a middle priority thread M is running instead of the highest priority thread H.

By blocking L, M is able to block H also: inversion.

See if you can code it up exactly like this.

Most modern schedulers have anti-deadlock safeguards that will change the priority for a time slice or two to prevent priority inversion leading to deadlocks, when detected or as deemed appropriate. Whether linux does with whichever scheduler you are using with it, I don't know for sure. However, do be aware of this, if you aren't already.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!