i've been wondering how multiple programs that run at the same time use the CPU registers without causing a conflict between the programs on the Windows OS.
does Windows OS uses a "virtual registers" to avoid such scenario(where multiple programs uses same registers simutaniously) ?
so if for example two programs use the eax
register does the OS really change the physical eax
register ?
or it uses some "virtual register" just like i've mentioned above ?
The operating system does not use virtual registers, the physical registers are changed.
In the old days machines only had one CPU core and only one thread was actually running at any point in time. Every time before a different thread can start running the OS kernel will save the state (registers) of the old thread and restore the state of the new thread before it can continue. This is called a context switch. The switch happens in kernel mode and if the thread it is switching to lives in a different process it also has to change the virtual memory mapping.
On a system with multiple cores multiple threads can run at the same time and each core has its own set of registers.
MSDN gives a rough overview of how context switching works on Windows:
The scheduler maintains a queue of executable threads for each priority level. These are known as ready threads. When a processor becomes available, the system performs a context switch. The steps in a context switch are:
- Save the context of the thread that just finished executing.
- Place the thread that just finished executing at the end of the queue for its priority.
- Find the highest priority queue that contains ready threads.
- Remove the thread at the head of the queue, load its context, and execute it.
...
The most common reasons for a context switch are:
- The time slice has elapsed.
- A thread with a higher priority has become ready to run.
- A running thread needs to wait.
If your program is running on a preemptive multitasking OS then you don't have to think about how and why context switches happen, you can just pretend you are always in control of the registers and that your program is the only program running.