Hi,
beyond infinity wrote:So far, I've understood. What I wanna know is: how to find out to which cpu to hand out a given task? say: I want to switch tasks on cpu0. or task X gave up cpu0. Now, cpu0 is already overloaded with work, and cpu1 is idle: let's give it to cpu1. How to determine the cpu? Are there special registers or locations?
Ahh
There's no special registers or anything, and there's no right/wrong way to do it (it mostly depends on how you want your scheduler to behave). I'll give a simplified description of what I do, as this should help..
First, start with "CPU affinity", which is just a bit mask (one bit for each CPU) that determines which CPUs the thread can be run on. This can be used by applications for performance reasons, and/or by the OS. It's also optional..
When a thread becomes ready to run, the scheduler checks each bit in it's CPU affinity bitmask and considers each "enabled" CPU. For each possible CPU you'd decide which one is the "best" one (this could mean the CPU with the least load, but (for HT) can also take into account the load on the physical CPU rather than just the load on logical CPUs).
For each CPU there's a "ready-to-run queue", which is sorted according to the priority of the threads on it. The highest priority thread is always at the top of the queue, and is the currently running thread. When a thread becomes ready-to-run the scheduler finds the best CPU (as above) and then inserts the thread into this queue according to it's priority. If the thread that just became ready-to-run is the highest priority thread on the queue then you'd probably want to pre-empt the currently running thread.
If the currently running thread becomes blocked for any reason (goes to sleep, is waiting for a message, gets terminated, etc) then you'd remove it from the CPU's ready-to-run queue, and select a new thread to run. When you're selecting the next thread to run, all you need to do is grab the thread on the top of the CPUs ready-to-run queue and run that.
Now, something I've missed is how you figure out which CPU has the most load. You could just keep track of the number of threads on each CPUs queue and use that, but you've probably already got some ideas of your own

.
That's all there is to it

. This scheduler would always run the highest priority thread that can run (prioritized co-operative). It simple enough, but it's also easy to change - for example, the "ready-to-run" queue could be sorted differently, or the CPU could run each thread in the list rather than just the first (highest priority) thread, or you can dynamically adjust priorities, or you could have more than one "ready-to-run" queue for each CPU (for e.g. one queue for high priority threads, one for normal threads and another for idle threads).
Cheers,
Brendan