Linux线程优先级设置

本程序会让系统失去I/O响应,不建议去运行!

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <signal.h>
#include <string.h>
void * thr_fun(void *arg)
{
 int policy, ret;
 struct sched_param param;
 //获取线程调度参数
 ret = pthread_getschedparam(pthread_self(), &policy, ¶m);
 if(ret!=0)
 {
 printf("pthread_getschedparam %s/n", strerror(ret) );
 exit(1);
 }
 if (policy == SCHED_FIFO)
 {
 printf("policy:SCHED_FIFO/n");
 }
 else if (policy == SCHED_OTHER)
 {
 printf("policy:SCHED_OTHER/n");
 }
 else if (policy == SCHED_RR)
 {
 printf("policy:SCHED_RR/n");
 }
 printf("param:%d/n", param.sched_priority); 
 long long i;
 while (1) {
 i++;
 i *= 2;
 }
 pthread_exit(NULL); 
}
int main(void)
{
 int ret;
 pthread_t tid;
 pthread_attr_t attr;
 int policy, inher;
 struct sched_param param;
 
 //初始化线程属性
 pthread_attr_init(&attr);
 //获取继承的调度策略
 ret = pthread_attr_getinheritsched(&attr, &inher);
 if (ret!=0)
 {
 printf("pthread_attr_getinheritsched/n%s/n", strerror(ret));
 exit(1);
 }
 //
 if (inher == PTHREAD_EXPLICIT_SCHED)
 {
 printf("PTHREAD_EXPLICIT_SCHED/n");
 }
 else if (inher == PTHREAD_INHERIT_SCHED)
 { 
 printf("PTHREAD_INHERIT_SCHED/n");
 inher = PTHREAD_EXPLICIT_SCHED;
 }
 //设置继承的调度策略
 //必需设置inher的属性为 PTHREAD_EXPLICIT_SCHED,否则设置线程的优先级会被忽略
 ret = pthread_attr_setinheritsched(&attr, inher);
 if (ret!=0)
 {
 printf("pthread_attr_setinheritsched/n%s/n", strerror(ret));
 exit(1);
 }

 

 /*linux提供了两种实时调度策略:SCHED_FIFO和SCHED_RR,实时调度策略比任何SCHED_NORMAL的进程
都优先得到调度。实时进程调度队列,是从优先级最高的进程运行, 如果当前运行的是SCHED_FIFO进程,
如果他不主动让出cpu,其他进程都不能运行 , 如果是SCHED_RR(时间片轮转)的,则不会一直独占cpu,
运行一段时间会被切换出来。*/
 policy = SCHED_FIFO;//在Ubuntu9.10上需要root权限
 //设置线程调度策略
 ret = pthread_attr_setschedpolicy(&attr, policy);
 if (ret!=0)
 {
 printf(" pthread_attr_setschedpolicy/n%s/n", strerror(ret));
 exit(1);
 }
 param.sched_priority = 3;
 //设置调度参数
 ret = pthread_attr_setschedparam(&attr, ¶m);
 if (ret!=0)
 {
 printf(" pthread_attr_setschedparam/n%s/n", strerror(ret));
 exit(1);
 }
 //创建线程
 ret = pthread_create(&tid, &attr, thr_fun, NULL);
 if (ret!=0)
 {
 printf("pthread_create/n%s/n", strerror(ret));
 exit(1);
 }
 while (1) {
 printf("hello world/n");
 }
 pthread_join(tid, NULL);
 pthread_exit(NULL);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值