Can a Coroutine is useful without Asynchronous IO ?

Coroutine is a way of doing concurrent programming without the need of Thread.
For more information regarding coroutine, go to asyncoro and asyncio-task.

Coroutine has numerous advantages when used with asynchronous IO. But in this post I am analyzing whether coroutine can be used without it and also checking whether coroutine can be used to replace threads in most scenarios as threads itself is not running in parallel due to GIL in python.

Below are the advantage and disadvantage of coroutines (without Asynchronous IO) when compared against threads.

Advantage
    1. No locking mechanism required (in most cases) as the next coroutine will run only after the current coroutine yields. 
     2.  No thread, so no context switch required between coroutine execution.
   
Disadvantage
    1. If a coroutine gets blocked, it will block all other coroutines as well as there is no preemption.
    2. All the coroutine should respect other coroutine as well, ie. if a coroutine running for a long time before it yields, no other corouting can get it chance to run.

Where coroutine can be used ?
    To answer this let make two assumptions.
        1. Coroutine have no blocking statements
        2. All coroutine will respect other coroutines
   
    If I make those two assumption then the next question that comes to my mind is that if there is no blocking statement and the coroutines will yield after performing some small set of task then why we need a concurrent execution, why not execute linearly ?
   
    The scenario I can think of is instead of poll for some resource and sleeping the thread if it not ready yet, we can preform that in a coroutine where we can check the poll value and yield with a sleep time as it can avoid unnecessary threads/context_switch for this.
   
    Other scenario can be, if a each coroutine produces a output before it yields and that output in used by some other external processes (runs in different CPU or system) for each routine to perform some activity, then by this way we reduce the waiting time of external processes when compated to executing all the routine linearly.
   
Conclusion
    From the above analysis, the coroutine has very limited scenario without using Asynchronous IO to be effective to replace the use threads. But it's my first look into coroutine concept. I pretty sure that this post will be updated a lot after I started digging more into this subject.

Comments

Popular posts from this blog

Different way to search for files in Gnome

Effective Use Of For Loop in Bash Shell Scripting