出于演示目的,我试图在一个小型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 这样的调度程序,非实时线程(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 桌面 11.04 上使用 g++ 4.5.2。