asyncio vs threading
- Python course
- Expert
- Lesson 35/47
- 5 min
Learn the difference between asyncio and threading.
asyncio vs threading
asyncio is a library that runs concurrent I/O work in a single thread. threading uses operating system threads.
In asyncio you define a coroutine with async def and wait for I/O with await. During the wait the event loop switches to another coroutine. In threading each thread has its own execution flow. asyncio is more efficient for I/O-bound server applications; but it is not suitable for CPU-bound work.
Starting with asyncio.run
You cannot call an async def function directly; it needs an event loop. asyncio.run(greet()) starts the event loop and runs the coroutine.
This is the standard entry point for asyncio programs. asyncio.run creates the loop, runs the coroutine and closes the loop when done. You call asyncio.run only once in a program. Inside you can await other coroutines.
Practice Call greet with asyncio
Import the module with import asyncio. Define async def greet(): that does print("async"). Run it with asyncio.run(greet()).
Starter code
# write an async greet function
# run it with asyncio.runSample solution
import asyncio
async def greet():
print("async")
asyncio.run(greet())Expected output
async
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the async definition
import asyncio
____ def greet():
print("async")
import asyncio
async def greet():
print("async")
Explanation: A coroutine is defined with async def.
2 Match asyncio vs threading concepts
| Term | Meaning |
|---|---|
async def |
Coroutine |
await |
Waits for I/O |
asyncio.run |
Event loop |
threading |
Thread |
3 Where is asyncio more efficient?
- CPU-bound computation
- I/O-bound server applications Correct answer
- Single-threaded simple programs
- File compression
Explanation: asyncio is more efficient than threading for I/O-bound server applications.