Junior — Middle
What components interact and share resources in the cooperative multitasking mechanism?
sobes.tech AI
Answer from AI
In the cooperative multitasking mechanism, the main components that interact and share resources are coroutines or tasks, which voluntarily yield control themselves, and the scheduler, which switches context between them.
Coroutines share memory, file descriptors, and other system resources, but switching occurs only when the coroutine explicitly passes control (for example, through yield in Python). This helps avoid races and conflicts, as switching happens at controlled points.
An example in Python using generators for cooperative multitasking:
def task1():
for i in range(3):
print(f"Task 1 - step {i}")
yield
def task2():
for i in range(3):
print(f"Task 2 - step {i}")
yield
# Simple scheduler
tasks = [task1(), task2()]
while tasks:
task = tasks.pop(0)
try:
next(task)
tasks.append(task)
except StopIteration:
pass
Here, coroutines (tasks) control their switching points themselves, and the scheduler simply calls them in turn.