Chinaunix
标题:
LINUX- C Pthread 线程优先级的问题....
[打印本页]
作者:
hanzhenlll
时间:
2012-07-18 14:21
标题:
LINUX- C Pthread 线程优先级的问题....
本帖最后由 hanzhenlll 于 2012-07-18 14:23 编辑
我本来想给别人提供下线程优先的例子,想自测一下,结果死活不通,为什么不能优先呢......... 变量名乱打的 请忽略.....
FIFO RR都试过,下午头晕晕 请教大牛给分析下,怎么让其中一个线程优先级高一些
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
void *fun_1 (const char *arg)
{
int i = 1, j =0;
float sum = 1.007;
pthread_detach (pthread_self());
while (1)
{
usleep (1);
printf ("sum 1-----111----->%3f\n", sum);
}
pthread_exit (NULL);
}
void *fun_2 (const char *arg)
{
int i = 1, j = 0;
float sum = 1.008;
pthread_detach (pthread_self());
while (1)
{
usleep (1);
printf ("sum 2-----222----->%3f\n", sum);
}
pthread_exit (NULL);
}
int main (void)
{
int abc;
pthread_attr_t attr;
struct sched_param param;
pthread_attr_init (&attr);
// pthread_attr_setinheritsched (&attr,&);
//pthread_attr_setschedpolicy (&attr, SCHED_FIFO);
pthread_attr_setschedpolicy (&attr, SCHED_RR);
param.sched_priority = 10;
pthread_attr_setschedparam (&attr, ¶m);
#if 1
#endif
pthread_t pid_1, pid_2;
int i = 0, j;
// while (i++ < 10)
// {
pthread_create (&pid_1, &attr, fun_1, NULL);
pthread_attr_destroy (&attr);
#if 0
pthread_attr_t attr2;
struct sched_param param2;
pthread_attr_init (&attr2);
// pthread_attr_setinheritsched (&attr2,PTHREAD_EXPLICIT_SEHED);
pthread_attr_setschedpolicy (&attr2, SCHED_RR);
param2.sched_priority = 90;
pthread_attr_setschedparam (&attr2, ¶m2);
#endif
pthread_create (&pid_2, NULL, fun_2, NULL);
// pthread_attr_destroy (&attr2);
//pthread_join (pid_1, NULL);
//pthread_join (pid_2, NULL);
// }
getchar ();
return 0;
}
复制代码
作者:
chen0610
时间:
2012-08-17 14:32
这些天也研究了这个优先级的问题,在网上找了些资料,自己也测试了一下可行。
在pthread_attr_setschedpolicy之前调用pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)就可以了。
PTHREAD_EXPLICIT_SCHED表示使用在schedpolicy和schedparam属性中显式设置的调度策略和参数,
如果不设置这项的话则表示新线程将继承创建线程的调度策略和参数。
使用pthread_attr_setschedparam进行设置的时候值越大代表优先级也越高。
编译的时候一定要加-lpthread选项,不然设置调度策略是不起作用的。
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2