gpt4 book ai didi

c - C 中默认调度程序的 pthread 良好值设置

转载 作者:行者123 更新时间:2023-11-30 20:57:26 25 4
gpt4 key购买 nike

我试图使用线程的 setpriority 设置好的值,但似乎无法让它以正确的方式工作。每当我执行获取优先级时,该值总是显示为-1。所以基本上我无论如何都无法设置任何好的值。

#include <stdio.h> 
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/resource.h>

static int var = 0;

void *my_inc()
{
setpriority(PRIO_PROCESS, pthread_self(), -10);
printf("thread 1 within %d \n", getpriority(PRIO_PROCESS, pthread_self()));
for(int i = 1; i < 10; i++)
{
var = i;
sleep(1);
printf("hi ");
}

pthread_exit(NULL);
}

void *my_print()
{
while(1)
{
printf("var %d\n", var);
sleep(1);
}
}

int main(void)
{
pthread_t thread_id1, thread_id2, thread_id3;

pthread_create(&thread_id1, NULL, my_inc, NULL);
printf("thread 1 before %d \n", getpriority(PRIO_PROCESS, thread_id1));
setpriority(PRIO_PROCESS, thread_id1, -10);

pthread_create(&thread_id3, NULL, my_print, NULL);
setpriority(PRIO_PROCESS, thread_id3, 10);

printf("thread 3 after %d \n", getpriority(PRIO_PROCESS, thread_id3));
printf("thread 1 after %d \n", getpriority(PRIO_PROCESS, thread_id1));

for(int j = 0; j < 20; j++)
{
printf("main %d ", j);
sleep(1);
}

pthread_join(thread_id1, NULL);
exit(0);
pthread_exit(NULL);
printf("After thread\n");
return 0;
}

最佳答案

我不清楚是什么让你认为 setpriority()函数将以任何方式适用于您尝试执行的任务。来自其文档:

The setpriority() function shall set the nice value of a process, process group, or user [...].

线程不是这些。

此外,

who is interpreted relative to which (a process identifier for PRIO_PROCESS, process group identifier for PRIO_PGRP, and a user ID for PRIO_USER).

您正在指定 PRIO_PROCESS 并传递线程标识符,但线程标识符不是进程 ID。与 pid_t 不同,pthread_t 甚至不需要是整数类型。因此,setpriority() 失败并返回 -1 并适当设置 errno 也就不足为奇了。如果您正确检查函数调用结果中的错误代码,您就会知道发生了这种情况。

也许您可以通过 pthread_setschedprio() 实现您的目标相反,函数。

关于c - C 中默认调度程序的 pthread 良好值设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59758558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com