在这里,我正在尝试创建两个线程,为它们分配优先级/策略并获得预期的行为。
预期的行为:具有最高优先级的线程(在这种情况下为thread1)应始终首先执行。 我看到的是:线程输出混杂在一起,这意味着没有遵循优先级。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sched.h>
void *thread_func1 ();
void *thread_func2 ();
int main (){
pthread_t thread1,thread2;
pthread_attr_t attr1,attr2;
struct sched_param param1,param2;
int thread1_prio = 70;
int thread2_prio = 69;
int policy1,policy2;
policy1 = SCHED_RR;
policy2 = SCHED_RR;
pthread_attr_init(&attr1);
pthread_attr_init(&attr2);
param1.sched_priority = thread1_prio;
param2.sched_priority = thread2_prio;
pthread_attr_setschedparam(&attr1,¶m1);
pthread_attr_setschedparam(&attr2,¶m2);
pthread_attr_setschedpolicy(&attr1,policy1);
pthread_attr_setschedpolicy(&attr2,policy2);
pthread_attr_getschedparam(&attr1,¶m1);
pthread_attr_getschedparam(&attr2,¶m2);
pthread_attr_getschedpolicy(&attr1,&policy1);
pthread_attr_getschedpolicy(&attr2,&policy2);
pthread_create(&thread1,&attr1,thread_func1,NULL);
pthread_create(&thread2,&attr2,thread_func2,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
void *thread_func1 (void *var){
for (int i = 0; i<5; i++){
printf("Thread: 1\n");
}
return 0;
}
void *thread_func2 (void *var){
for (int i=0; i<5; i++){
printf("Thread: 2\n");
}
return 0;
}
- 我也尝试使用
pthread_setschedprio
,但仍然无法获得预期的结果。 - 以
root
的身份执行程序
在发布此问题之前,我确实尝试关注许多帖子/示例,但最终变得更加困惑。任何帮助表示赞赏。
编辑:这不是一个真正的问题吗?我的意思是,如果发布此消息很愚蠢,请纠正我,并应得下票,因为其中一些人已经对该帖子投了反对票?