不能在C中引发优先级倒置
作者:互联网
我试图在一个小的C程序上激发优先级反转以进行演示,但我不能:持有互斥锁的低优先级线程没有被抢占并继续在关键部分运行.这就是我正在做的事情:
// let's declare a global mutex
pthread_mutex_t my_mutex;
...
int main(int argc, char **argv) {
...
pthread_t normal_thread;
pthread_t prio_thread;
pthread_mutexattr_t attr;
pthread_mutexattr_init (&attr);
pthread_mutexattr_setprotocol (&attr, PTHREAD_PRIO_NONE); // ! None !
pthread_mutex_init(&my_mutex, &attr);
// create first normal thread (L):
pthread_create(&normal_thread, NULL, the_locking_start_routine, NULL);
// just to help the normal thread enter in the critical section
sleep(2);
// now will launch:
// * (M) several CPU intensive SCHED_FIFO threads with priority < 99
// * (H) one SCHED_FIFO thread that will try to lock the mutex, with priority < 99
// build Real Time attributes for the Real Time threads:
pthread_attr_t my_rt_att;
pthread_attr_init(&my_rt_att);
// it was missing in the original post and it was also wrong:
// even setting the SchedPolicy you have to set "InheritSched"
pthread_attr_setinheritsched(&my_rt_att, PTHREAD_EXPLICIT_SCHED)
pthread_attr_setschedpolicy(&my_rt_att, SCHED_FIFO);
struct sched_param params;
params.sched_priority = 1;
pthread_attr_setschedparam(&my_rt_att, ¶ms);
pthread_create(&prio_thread, &my_rt_att, the_CPU_intensive_start_routine, NULL)
params.sched_priority = 99;
pthread_attr_setschedparam(&my_rt_att, ¶ms);
// create one RealTime thread like this:
pthread_create(&prio_thread, &my_rt_att, the_locking_start_routine, NULL) //coma was missing
...
}
void *the_locking_start_routine(void *arg) {
...
pthread_mutex_lock(&my_mutex);
// This thread is on the critical section
// ... (skipped)
pthread_mutex_unlock(&my_mutex);
...
}
…但它不起作用,我不能有我想要的优先级倒置.
这是发生的事情:
据我所知,使用像Linux的CFS这样的scheduller,非实时线程(SCHED_OTHER)将不会运行,直到没有任何实时线程(SCHED_FIFO或SCHED_RR)处于运行状态.但我已经实现了同时运行的这些线程:
>(L)一个非实时(SCHED_OTHER)线程锁定互斥锁和
消耗CPU
>(M)几个实时线程(SCHED_FIFO,& priority> 0)CPU
密集和不等待锁定互斥锁
>(H)一个实时线程(SCHED_FIFO,&最高优先级)等待
为了锁
运行的实时CPU密集型线程(M)比我的系统的CPU数量多……但非实时线程持有(L)锁仍然消耗CPU并完成它的工作并在之前释放互斥锁“M”线程完成消耗CPU.
为什么低优先级线程不被抢占,应用程序死锁,我无法获得优先级倒置?
我在内核2.6.38-13的Ubuntu Desktop 11.04上使用g 4.5.2.
解决方法:
>您是否以root身份运行该程序?
>您对这些sysctl参数的值是什么?这是我的Ubuntu盒子.默认设置是在1秒切片中仅提供0.95秒的实时时间:
kernel.sched_rt_period_us = 1000000
kernel.sched_rt_runtime_us = 950000
这可以防止实时域占用所有CPU.如果您想要实时,则必须禁用这些参数.
见:http://www.kernel.org/doc/Documentation/scheduler/sched-rt-group.txt
如果将sched_rt_runtime_us设置为-1,则禁用此安全机制.
标签:thread-priority,c,pthreads,mutex,real-time 来源: https://codeday.me/bug/20190723/1513463.html