Sobes.tech
Junior — Middle

What are the differences between cooperative and preemptive multitasking mechanisms in Python, and how are they implemented?

sobes.tech AI

Answer from AI

In Python, there are two main mechanisms of multitasking:

  1. Preemptive multitasking — when the operating system itself switches contexts between threads or processes without the involvement of the code. In Python, this is implemented through the threading and multiprocessing modules. However, due to the GIL (Global Interpreter Lock), threads do not execute in parallel on multiple cores, but processes do.

  2. Cooperative multitasking — when context switching occurs explicitly in the code, for example, through asyncio and await. Here, tasks voluntarily yield control, allowing efficient handling of a large number of I/O operations.

Example of cooperative multitasking with asyncio:

import asyncio

async def task(name, delay):
    print(f"Task {name} starts")
    await asyncio.sleep(delay)
    print(f"Task {name} finished")

async def main():
    await asyncio.gather(task('A', 1), task('B', 2))

asyncio.run(main())

Thus, preemptive multitasking is managed by the OS, while cooperative multitasking is managed by the application through explicit switch points.