当前位置: 技术问答>linux和unix
Linux线程调度策略SCHED_FIFO不能进行高优先级抢占?
来源: 互联网 发布时间:2017-05-29
本文导语: 下面这段代码是我写来测试使用SCHED_FIFO调度策略时线程运行情况的,其中Thread1和Thread2的优先级分别为10和11,即Thread2的优先级较高。按我的理解,Thread2应该能够抢占Thread1的CPU控制权,即每秒打印一次Thread2。然而程...
下面这段代码是我写来测试使用SCHED_FIFO调度策略时线程运行情况的,其中Thread1和Thread2的优先级分别为10和11,即Thread2的优先级较高。按我的理解,Thread2应该能够抢占Thread1的CPU控制权,即每秒打印一次Thread2。然而程序编译后运行,SHELL和系统都直接死掉了,必须重启虚拟机。如果我把被注释的两句代码任意一句打开,则可以正常运行。似乎是必须低优先级线程主动释放CPU控制权,高优先级任务才能执行,这样还要优先级有何用?我刚接触Linux编程没多久,有点弄不清楚Linux提供的实时调度机制有什么意义了,有没有人能够指点一二?谢谢!
#include
#include
#include
#include
pthread_t createSchedFifoThread(void* (*pThreadFunc)(void*), int priority)
{
struct sched_param param;
int policy;
int ret;
pthread_t id;
ret = pthread_create(&id, NULL, pThreadFunc, NULL);
if(ret != 0)
{
printf("pthread_create() error!n");
return 0;
}
param.sched_priority = priority;
policy = SCHED_FIFO;
ret = pthread_setschedparam(id, policy, ¶m);
if(ret != 0)
{
printf("pthread_setschedparam() error!n");
return 0;
}
return id;
}
void* thread1(void* arg)
{
sleep(1);
while(1);
{
//printf("thread1n");
//usleep(1);
}
}
void* thread2(void *arg)
{
sleep(1);
while(1)
{
printf("thread2n");
sleep(1);
}
}
int main(void)
{
pthread_t id;
id = createSchedFifoThread(thread1, 10);
id = createSchedFifoThread(thread2, 11);
while(1)
{
sleep(1);
}
return 0;
}
|
unbuntu12.04正常,应该是虚拟机的问题
结果:
pthread_setschedparam() error!
pthread_setschedparam() error!
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
.......
结果:
pthread_setschedparam() error!
pthread_setschedparam() error!
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
.......
|
$ sudo ./thread_prio_research
[sudo] password for ***:
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
在管理员下运行,没有开始的错误了,结果依然正常
[sudo] password for ***:
thread2
thread2
thread2
thread2
thread2
thread2
thread2
thread2
在管理员下运行,没有开始的错误了,结果依然正常