asyncio — single-threaded concurrency. threading — multi-threaded parallelism.
1import asyncio2import threading3import time45# asyncio — single thread, cooperative6async def async_fetch(url):7 await asyncio.sleep(1) # Yields control8 return f"Data from {url}"910async def async_main():11 tasks = [async_fetch(f"url{i}") for i in range(5)]12 return await asyncio.gather(*tasks)1314# threading — multiple threads, preemptive15def thread_fetch(url):16 time.sleep(1) # Blocks thread, GIL released17 return f"Data from {url}"1819def thread_main():20 threads = [21 threading.Thread(target=thread_fetch, args=(f"url{i}",))22 for i in range(5)23 ]24 for t in threads:25 t.start()26 for t in threads:27 t.join()
Comparison: