进程调度API之set_user_nice

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);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值