void set_user_nice(struct task_struct *p, long nice)
用于设置进程的nice值.
其使用的例程如下:
static int kmemleak_scan_thread(void *arg)
{
static int first_run = 1;
pr_info("Automatic memory scanning thread started\n");
set_user_nice(current, 10);
}
其源码分析如下:
void set_user_nice(struct task_struct *p, long nice)
{
bool queued, running;
int old_prio, delta;
struct rq_flags rf;
struct rq *rq;
#如果当前task的nice值已经等于要设置的nice值,就直接退出
#从这里可以看出nice值的范围在-20~19 之间
if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
return;
/*
* We have to be careful, if called from sys_setpriority(),
* the task might be in the middle of scheduling on another CPU.
*/
rq = task_rq_lock(p, &rf);
update_rq_clock(rq);
/*
* The RT priorities are set via sched_setscheduler(), but we still
* allow the 'normal' nice value to be set - but as expected
* it wont have any effect on scheduling until the task is
* SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
*/
#如果当前是实时进程,这里也可以看出实时进程的的调度策略可以分为deadline/fifo/rr.
#针对实时进程设置nice值其实是没有作用的,但是这里还是将nice值转成优先级后设置到p->static_prio
if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
p->static_prio = NICE_TO_PRIO(nice);
goto out_unlock;
}
queued = task_on_rq_queued(p);
running = task_current(rq, p);
if (queued)
dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
if (running)
put_prev_task(rq, p);
#将nice值转成优先级设置到static_prio 中,#define NICE_TO_PRIO(nice) ((nice) + DEFAULT_PRIO)
#这里的DEFAULT_PRIO 值经过计算是120.
#从这里也可以看出优先级转nice值应该是减去DEFAULT_PRIO #define PRIO_TO_NICE(prio) ((prio) - DEFAULT_PRIO)
p->static_prio = NICE_TO_PRIO(nice);
set_load_weight(p);
old_prio = p->prio;
p->prio = effective_prio(p);
delta = p->prio - old_prio;
#如果要设置的nice的task在queue中
if (queued) {
enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
/*
* If the task increased its priority or is running and
* lowered its priority, then reschedule its CPU:
*/
#如果增大优先级且task正在运行或者减小优先级的话,则重新调度rq。
if (delta < 0 || (delta > 0 && task_running(rq, p)))
resched_curr(rq);
}
#如果要设置nice值的task正在运行,由于我们这里改变了p的优先级,则重新指定task的rq.
if (running)
set_curr_task(rq, p);
out_unlock:
task_rq_unlock(rq, p, &rf);
}
进程调度API之set_user_nice
最新推荐文章于 2025-03-26 00:14:41 发布