Junior — Middle
Explain the differences between preemptive multitasking and cooperative multitasking models.
sobes.tech AI
Answer from AI
Preemptive multitasking and cooperative multitasking differ in the way they switch between tasks:
-
Preemptive: the operating system or scheduler interrupts the current task to give time to another. This ensures a fairer distribution of resources and prevents system hang-ups caused by a single task.
-
Cooperative: tasks decide themselves when to yield control to others. If a task does not yield, others may not get processor time, which can lead to hangs.
Example in Python:
import threading
import time
def task():
for i in range(5):
print(i)
time.sleep(1) # here, time is yielded to other threads
thread = threading.Thread(target=task)
thread.start()
In Python, threads operate with preemption, as the interpreter periodically switches execution between threads.