我试图在Linux中使用
设置低优先级[priority = 10]
pthread_setschedparam()
然而,我从函数中得到的可接受值
sched_get_priority_{min|max}()
为0-99。
如果我给1,我优先考虑-2 如果我给90,我优先考虑-90 但我希望获得优先权10。
代码如下。有没有办法为线程分配低优先级。
[注意 - 我还尝试了 setpriority ,但这在我的情况下不起作用,因为我需要从主线程中分配优先级]
#include <pthread.h>
#include <errno.h>
#include <string.h>
void *print_message_function( void *ptr );
main()
{
pthread_t thread1, thread2;
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int iret1, iret2;
struct sched_param sch_params;
//sch_params.sched_priority = 5;
sch_params.sched_priority = 10;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
if(iret1)
{
printf("Error - pthread_create() return code: %d\n",iret1);
exit(EXIT_FAILURE);
}
if(pthread_setschedparam(thread1, SCHED_RR, &sch_params)) {
printf( "Failed to set thread's priority : %s \n",strerror(errno));
} else {
printf( "thread priority is set properly: \n");
}
pthread_join( thread1, NULL);
exit(EXIT_SUCCESS);
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
while (1) {
printf("%s \n", message);
sleep(1);
}
}