zircon 实现两种调度机制,一种就是fair 其实现在fair_scheduler.cpp中,一种是基于时间片的其实现在sched.cpp 中,调度器的入口都在sche_reschedule()这个函数中。
例如fair的实现如下:
void sched_reschedule() {
FairScheduler::Reschedule();
}
fair的实现是一个cpp的类。
另一中sche_reschedule()的实现在sched.cpp 中,我们简单看下
void sched_reschedule() {
current_thread->state = THREAD_READY;
// idle thread doesn't go in the run queue
if (likely(!thread_is_idle(current_thread))) {
#可见会首先判断当前线程的时间片是否用尽,用尽的话,则加入到当前cpu 运行队列的末尾,否则就插入到head,这样下次调用这个函数的时候就会
优先调用这个函数
if (current_thread->remaining_time_slice > 0) {
insert_in_run_queue_head(curr_cpu, current_thread);
} else {
insert_in_run_queue_tail(curr_cpu, current_thread);
}
}
sched_resched_internal();
}
void sched_resched_internal() {
thread_t* current_thread = get_current_thread();
uint cpu = arch_curr_cpu_num();
CPU_STATS_INC(reschedules);
// pick a new thread to run
#从当前cpu 挑选一个thread 来运行,类似于linux的RR调度
thread_t* newthread = sched_get_top_thread(cpu);
DEBUG_ASSERT(newthread);
newthread->state = THREAD_RUNNING;
thread_t* oldthread = current_thread;
oldthread->preempt_pending = false;
#计算久进程的时间记账
zx_time_t now = current_time();
// account for time used on the old thread
DEBUG_ASSERT(now >= oldthread->last_started_running);
zx_duration_t old_runtime = zx_time_sub_time(now, oldthread->last_started_running);
oldthread->runtime_ns = zx_duration_add_duration(oldthread->runtime_ns, old_runtime);
oldthread->remaining_time_slice = zx_duration_sub_duration(
oldthread->remaining_time_slice, MIN(old_runtime, oldthread->remaining_time_slice));
// set up quantum for the new thread if it was consumed
if (newthread->remaining_time_slice == 0) {
newthread->remaining_time_slice = THREAD_INITIAL_TIME_SLICE;
}
newthread->last_started_running = now;
#切换mmu
// see if we need to swap mmu context
if (newthread->aspace != oldthread->aspace) {
vmm_context_switch(oldthread->aspace, newthread->aspace);
}
#进程切换
// do the low level context switch
final_context_switch(oldthread, newthread);
}