Async Tasks, Threads, and Processes
Compare cooperative waiting, threads, and separate processes without promising an execution order.
python, asyncio, concurrency, threads, processes, gilWaiting is not the same as parallel work
Concurrency lets multiple tasks make progress over time; parallelism means
work runs simultaneously. asyncio uses an event loop and cooperative
suspension, threads share process memory, and processes have separate
memory spaces. Choose based on the workload and communication costs.
Python illustration
import asyncio
async def double(number):
await asyncio.sleep(0)
return number * 2
async def main():
results = await asyncio.gather(double(2), double(3))
print(results)
asyncio.run(main())
Prepared output — not live execution:
[4, 6]
gather schedules the coroutines and returns results in argument order,
not necessarily completion order. sleep(0) yields control; it does not
promise which task runs next. The timeline below is one possible schedule.
See the reasoning
Explore one possible async schedule
Follow two coroutine lanes while they yield and return. This is a prepared demonstration, not live code execution.
Schedule both calls
- mainawait gatherCurrent focus
- double(2)ready
- double(3)ready
gather schedules both coroutines and waits for their results.
Choosing and cleaning up
Async works well for many cooperative I/O waits, provided code does not block
the event loop. Threads can help with blocking I/O and share memory, so
shared mutable state needs coordination. In ordinary CPython builds, the
global interpreter lock (GIL) limits simultaneous Python bytecode execution;
some extension code releases it, and optional free-threaded builds differ.
Processes can use multiple cores for CPU work but have startup, serialisation,
and communication costs. On spawn-based platforms, protect process startup
with if __name__ == "__main__":.
The standard-library executor interface illustrates both choices:
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def square(number):
return number * number
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=2) as threads:
print(list(threads.map(square, [2, 3])))
with ProcessPoolExecutor(max_workers=2) as processes:
print(list(processes.map(square, [2, 3])))
Run this example from a Python file so worker processes can import square.
Both prepared output lines are [4, 9]: map returns results in input order,
not necessarily execution order. Such tiny calculations do not justify process
startup; the example illustrates the interface, not a performance claim.
Await tasks, handle failures and cancellation, and close resources. Neither
the GIL nor async alone makes a compound operation race-free. Avoid
assuming a specific task ordering unless the program explicitly coordinates it.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
