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:
asynciomodule — allows writing asynchronous code using coroutines, event loops, and theasync/awaitkeywords.
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())
- 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()
-
concurrent.futuresmodule withThreadPoolExecutororProcessPoolExecutor— for convenient management of thread or process pools. -
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.