Skip to content

Scheduler and Threads

Oguzhan KAYNAK edited this page Dec 3, 2026 · 3 revisions

Scheduler and Threads

The scheduler is cooperative by design: a thread runs until it calls yield, sleep or block, waits for something, or ends. The 1 ms timer only counts ticks. It runs threads only, all in one list (linked through the threads themselves, so there is no limit but memory), round robin, with no priorities: which process a thread belongs to is not its business.

A thread finds its scheduler through the current task (Threading::currentTask(), set on every switch): Threading::yield(), sleep(ms), exitThread(code) and currentThread() act on the running thread, and Thread(entry, arg) goes to the caller's scheduler.

int64_t worker(void* arg)
{
    auto rounds = reinterpret_cast<int64_t>(arg);
    for (int64_t i = 0; i < rounds; i++) {
        doSomething();
        Threading::yield();
    }
    return rounds; // the exit code: returning ends the thread
}

auto* t = new Threading::Thread(worker, reinterpret_cast<void*>(10));
int64_t code = t->wait(); // 10
delete t;                 // the destructor waits too, had nobody waited

User programs have the same class with the same names (User::Threading::Thread), see User Programs.

Several schedulers can exist; the self tests build their own on a fake tick source. Thread(scheduler, space, entry, arg) names the scheduler and the address space of the stack explicitly.

The sync objects use the current task the same way, so they are plain values: Sync::Semaphore sem(0, 1);, Sync::Mutex m;, Sync::ConditionVariable cv;.

Call Effect
yield() run the next runnable thread (round robin)
sleep(ms) sleep for at least ms ticks
block() / unblock(tcb) wait until someone unblocks the thread
exitThread(code) end the current thread (returning from the entry does the same)
Thread::wait() sleep until the thread has ended, then its exit code
Thread::id(), currentThread() thread ids: the pid above, a number below (kernel threads are process 0: 0.1, 0.2, ...)
ticks(), taskCount(), current(), firstTask()/nextTask() state queries
Threading::currentTask(), currentScheduler() the running task and its scheduler

Each kernel thread has its own 2 MB stack page. When nothing can run, the idle thread halts the CPU until the next interrupt. The shell shows the threads with tasks, their CPU time with sched and top.

More: kernel/sched/README.md

Clone this wiki locally