Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How exactly is a coroutine suspended?

From the kotlin docs

A coroutine is an instance of suspendable computation. 
It may suspend its execution in one thread and resume in another one.
delay is a special suspending function. 
It suspends the coroutine for a specific time. 
Suspending a coroutine does not block the underlying thread, but allows other coroutines to run and use the underlying thread for their code.

When a coroutine is suspended the thread which was running it is free to execute some other coroutine. For example when you use delay() or callSomeAPI() they are done asynchronously.

I come from javascript world. There functions like setTimeout() or fetch() were executed outside of javascript callstack and inside the browser environment.

But in our kotlin case who exactly is executing those methods? Shouldn't there be a thread which manages stuff? So do we start a new thread to take care of the async code in coroutines?

like image 232
Charan Sai Avatar asked Jan 25 '26 02:01

Charan Sai


1 Answers

It really depends on what is the reason to suspend. For example, if we suspend to wait for some IO, then it is probable that underneath another thread is used to block on this IO. Some IO are event-based, so OS notifies our application that the coroutine could be resumed. But in many cases we suspend waiting for another coroutine, for example we wait for its completion or we wait on reading from/writing to a Channel (suspendable queue). Then, there is no need for additional thread - other coroutines resume our coroutine. delay() is another example. I'm not sure how does it work internally, it definitely depends on the target platform, but I don't suspect it to do busy-waiting ;-) I guess there is some kind of a timer event provided by the OS.

So once again: it depends.

like image 80
broot Avatar answered Jan 26 '26 23:01

broot