Sobes.tech
Junior — Middle

What methods can be used to perform asynchronous task execution within a single process?

sobes.tech AI

Answer from AI

In Python, asynchronous execution of tasks within a single process can be implemented using the following methods:

  1. asyncio module — allows writing asynchronous code using coroutines, event loops, and the async/await keywords.
import asyncio

async def task():
    print('Task start')
    await asyncio.sleep(1)
    print('Task completed')

async def main():
    await asyncio.gather(task(), task())

asyncio.run(main())
  1. Threads (threading) — enable running multiple threads in parallel, useful for I/O-bound tasks.
import threading
import time

def task():
    print('Task start')
    time.sleep(1)
    print('Task completed')

threads = [threading.Thread(target=task) for _ in range(2)]
for t in threads:
    t.start()
for t in threads:
    t.join()
  1. concurrent.futures module with ThreadPoolExecutor or ProcessPoolExecutor — for convenient management of thread or process pools.

  2. Generators and coroutines (before asyncio) — a lower-level approach, now rarely used.

Thus, for asynchronous execution within a single process, asyncio or threads are most commonly used.