+ 6
Kotlin coroutine vs thread?
Can expect any help to understand about coroutine in kotlin vs thread?☺️☺️ Any post although I know it's hard topic to understand easily. But I really want to understand it. please I have watched videos but I am confused about scope of corutine and how it's none blocking. Although I know about continuation I have understand it by java byte code where it add the further part as continuation.
5 Respuestas
+ 6
Repeating DM answer here for others.
Coroutines run synchronously under program control so they choose when they want to stop to let something else run. Threads are timesliced by the OS to run asynchronously so they have no clue when they are stopped for other things to run. Personally, I'd never use threads and have always only used coroutines in my programming, even when language support was not available. Coroutines are much easier to debug as you know when they give up their turn. Threads can give up their turn in the middle of a language statement as each hardware instruction can be the place the OS picks to switch it.
You don't need to add code to protect things that can't be executed by two threads simultaneously with coroutines as it will never happen. Most thread code I've fixed over the decades will never be bug free because there are way to many places the OS can stop you that it is impossible to find all issues.
+ 5
No, the coroutines are switch in the Kotlin library code. If you place a set of coroutines in one thread and second set in another thread, the OS will deal with the threads possible running each in two cores at the same time, which is why you must protect things that can't be used by them at the same moment. The set of coroutines will be swapped by the library code, when they choose to allow it. Doing this means your coroutine sets either can never interact or must have thread based protection where they interact.
+ 4
Thank you sir
+ 2
John Wells
Since the JVM is quite high level, aren't both coroutines and threads subject to the OS' thread scheduling?
(also to answer the question coroutines are nicer to work with than threads)
+ 2
Ah, thanks!