Preemptive and Non-Preemptive AKA Cooperative scheduling/multitasking
Preemptive and cooperative multitasking are two different approaches to managing multiple processes or threads within an operating system.
Preemptive multitasking involves the operating system interrupting a running process or thread and switching to another process or thread, regardless of whether the running process or thread has completed its task or not. This is done based on priority levels assigned to different processes or threads. In preemptive multitasking, the operating system takes control of the CPU and decides which process or thread gets to execute.
On the other hand, cooperative multitasking involves each process or thread voluntarily yielding control to other processes or threads after completing its task. In cooperative multitasking, the running process or thread must explicitly give up control to allow other processes or threads to execute.
Here are some examples to illustrate the differences between preemptive and cooperative multitasking:
Example 1: Preemptive Multitasking Consider a scenario where an operating system has two processes A and B with different priorities. Process A has higher priority than process B. If process A is running and the operating system detects that process B has become ready to run, it may interrupt process A and switch to process B to ensure that higher priority process is not kept waiting.
Example 2: Cooperative Multitasking Consider a scenario where an operating system has two threads T1 and T2. T1 starts executing and performs some work, and then it voluntarily yields the CPU to allow T2 to execute. T2 also performs some work and then yields the CPU back to T1. This continues until both threads have completed their tasks.
Preemptive multitasking is generally used in modern operating systems as it provides better control over the execution of processes or threads, and helps in preventing processes or threads from monopolizing the CPU. However, preemptive multitasking can also result in processes or threads being interrupted at critical points, which can lead to issues such as race conditions or deadlocks. Cooperative multitasking, on the other hand, is less commonly used due to its reliance on processes or threads to voluntarily yield control to other processes or threads, which can lead to issues such as starvation or inefficiency.