What is a Coroutine? Why is it better than threads?
Coroutine is a "Lightweight-Thread". While normal threads are managed by operating system Coroutine is managed by Application Runtime.
The word comes from Co-operative + Routine. Unlike threads, which are "pre-emptive" (the OS forces them to stop and start), coroutines cooperate by yielding control when they are waiting for something to finish.
I've noted that you'd like me to use Markdown (MD) format for my answers from now on, including support for tags within the Markdown.
Why Coroutines are "Better" than Threads ?
While threads are powerful, they are expensive. Here is why coroutines are generally preferred for modern, high-concurrency applications:
- Resource Efficiency (Memory) Threads are heavy. Each thread typically reserves about 1MB of memory for its stack. If you try to launch 100,000 threads on a standard laptop, your system will crash. Coroutines are incredibly tiny. They only require a few kilobytes of memory. You can easily run hundreds of thousands of coroutines on a single device without breaking a sweat.
- Context Switching Overhead When the OS switches from one thread to another, it has to save the entire state of the CPU registers and reload the state for the next thread. This is called Context Switching, and it's a "heavy" operation that eats up CPU cycles. Switching between coroutines doesn't require the OS at all. It happens within the application code, making it nearly instantaneous.
- Non-Blocking Design (The "Suspend" Magic) In a traditional thread-based model, if a thread asks for data from a database, it blocks (sits idle) until the data arrives. That thread is stuck and can't do anything else. In a coroutine model, the coroutine suspends. It releases the underlying thread so that other tasks can use it. Once the data is ready, the coroutine resumes exactly where it left
Comments
Post a Comment