Junior — Middle
Can you explain the concept of cooperative multitasking in a computing system?
sobes.tech AI
Answer from AI
Cooperative multitasking is a method of organizing the execution of multiple tasks (processes or threads), where switching between them occurs only when the current task voluntarily yields control. That is, the task itself decides when to pass control to another task, usually by calling a special function or completing its work.
Unlike preemptive multitasking, where the operating system forcibly switches tasks, cooperative multitasking requires programs to behave correctly, otherwise one task may 'hang' and block others.
An example in Python is using generators or coroutines, which explicitly pass control:
def task1():
for i in range(3):
print(f"Task 1 - step {i}")
yield # yield control
def task2():
for i in range(3):
print(f"Task 2 - step {i}")
yield
# Simple cooperative multitasking scheduler
t1 = task1()
t2 = task2()
for _ in range(3):
next(t1)
next(t2)
Here, yield is the point where the task voluntarily passes control, allowing another task to run.