I have a basic understanding of coroutines. From w...
# getting-started
b
I have a basic understanding of coroutines. From what I know, when using threads, the operating system handles context switching. However, with coroutines, the software itself manages context switching, and coroutines run on top of threads. Coroutines are often described as "lightweight threads" because they don't require the Thread Control Block (TCB) that threads use. One concept I struggle to understand is the claim that "coroutines don’t block the main thread while suspended." For example, if I want to download a file using a
suspend
function, the coroutine gets suspended, pausing its execution. However, the file still needs to be downloaded by some thread, meaning that the thread is actively working on the task. Why, then, can’t we say that this is blocking the thread?
j
A thread most likely gets blocked, but it would be easier to illustrate your question with some sample code so we can explain more precisely what's going on
b
Copy code
suspend fun downloadFiles(url : String) {
    launch(Dispatcher.IO) {
        download() // <----- Coroutine will suspend here and will resume after downloading a file 
    }
}
My confusion is My coroutine is suspended and no thread is blocked then we is downloading the file
d
There is a difference between suspending and blocking. If the
download
function is suspending, it will likely suspend until there is data available (often this is handle via a selector loop). If it is NOT
suspend
, then it is blocking, and does indeed block the thread.
1
j
By the way, the code you provided doesn't compile. You probably meant
withContext
instead of
launch
, but that changes quite a bit what's happening. That being said, as Daniel said, it really depends on whether
download
is blocking or suspending, and how the suspension is handled inside the function.