Coroutine — Explained with Examples
A coroutine is a cooperative multitasking construct that can suspend execution and resume later, enabling non-blocking concurrent code.
Coroutines are functions that can pause (suspend) at specific points and later resume from where they left off. Unlike threads, coroutines are cooperative — they voluntarily yield control rather than being preempted by the OS. This makes context switching very cheap (user-space only). Python’s async/await, Kotlin’s coroutines, and C++20 coroutines implement this pattern.
Think of a coroutine like a bookmark in a book. You read some pages, place the bookmark (suspend), go do something else, return later, and continue reading from the bookmark (resume). You never lose your place, and you don’t need a separate reader (thread) for each book.
Coroutines excel at I/O-bound tasks where most time is spent waiting for network or disk. They avoid thread overhead while maintaining readable sequential code.
import asyncio
async def fetch_data(url, delay):
print(f"Fetching {url}...")
await asyncio.sleep(delay) # Simulate network I/O
print(f"Done fetching {url}")
return f"Data from {url}"
async def main():
# Run coroutines concurrently
tasks = [
fetch_data("api.example.com/users", 2),
fetch_data("api.example.com/posts", 1),
fetch_data("api.example.com/comments", 1.5),
]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
asyncio.run(main())
# Output (timing varies):
# Fetching api.example.com/users...
# Fetching api.example.com/posts...
# Fetching api.example.com/comments...
# Done fetching api.example.com/posts
# Done fetching api.example.com/comments
# Done fetching api.example.com/usersCoroutines are the foundation of modern async programming in Python, Kotlin, C++, and other languages. They provide thread-like concurrency without thread overhead.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro