In a computer, the processor executes different threads and changes between them, the operating system is a program at the end that it´s being executed by the processor, there exists the posibility that the processor is not executing the code of the operating system, if there is, shouldn´t this cause problems with the programs being executed on the computer?
For full detail, you should consult a textbook on operating systems.
The brief answer is that the operating system doesn't need to be executing all the time. It suffices for it to periodically regain control of the machine, and this happens through so-called "interrupts". Interrupts can happen for a number of reasons:
- a process that wants the operating system to do something for it (e.g., to perform I/O) can raise an interrupt (known as a "system call");
- a hardware device that needs attention (e.g., because some I/O that was requested has now completed) alerts the OS by raising an interrupt;
- the system clock will raise interrupts at some frequency (typically multiple times per second).