Sobes.tech
Junior — Middle

Is it possible to perform multiple tasks simultaneously in one thread in Python?

sobes.tech AI

Answer from AI

In Python, it is possible to perform multiple tasks concurrently within a single thread using asynchronous programming (asyncio) or generators, which allow switching between tasks without creating new threads. However, due to the GIL (Global Interpreter Lock) in the standard CPython implementation, the concurrent execution of multiple threads running Python code is limited — only one thread executes at any given time.

An example with asyncio for concurrent task execution in a single thread:

import asyncio

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

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

asyncio.run(main())

Thus, multiple tasks can run 'in parallel' within a single thread, switching based on wait times, but not simultaneously in the sense of multithreading.