Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are coroutines just syntactic sugar around completion handlers?

Are coroutines just syntactic sugar around completion blocks and completion blocks will be created under the hood? Or is the concept of coroutines much more complex and broad then just compiler trick aka syntactic sugar

like image 986
denis631 Avatar asked Sep 12 '17 10:09

denis631


3 Answers

It's not just syntactic sugar, not at all. Coroutines do not block threads, they just suspend execution, thus they encourage non-blocking concurrent programming.

Coroutines do not rely on features of the operating system or the JVM (e.g. they are not mapped to native Threads). Instead, coroutines and suspend functions particularly are transformed by the compiler producing a state machine capable of handling suspensions in general and passing around suspending coroutines keeping their state. This is enabled by Continuations, which are added as a parameter to each and every suspending function by the compiler; this technique is called “Continuation-passing style”.

For details please have a look at https://github.com/Kotlin/kotlin-coroutines/blob/master/kotlin-coroutines-informal.md

like image 68
s1m0nw1 Avatar answered Sep 28 '22 01:09

s1m0nw1


No, coroutines are not syntactic sugar. You can think of coroutines as of functions that can interact with the caller. When you call a normal function, say foo you pass control to foo and have to wait until foo either completes or throws exception. Coroutines are functions which can pass control back to caller, and caller can decide whether coroutine should continue and when and how coroutine should continue. This gives opportunity to implement things which are special language constructs in other languages:

  • Generators (aka yield keyword) like in C# and JavaScript. Caller continues execution of coroutine when a user wants new value from iterator. Coroutine passes back to caller by calling yield() function, which also passes some value to caller.
  • Async/await like in C# and JavaScript. Caller continues execution when Future (similar to Task or Promise) gets resolved. Coroutine passes back to caller by calling await() function. Caller passes value to coroutine when Future gets resolved and coroutine observes this value as a result of await() call.
  • Goroutines/channels in Go.

Unlike C#, JavaScript or Go, Kotlin does not implement any of these features in special syntax. Instead, Kotlin provides only suspend fun syntax, and then you can implement these features yourself (or get existing one from corresponding library called kotlinx.coroutines).

like image 31
Alexey Andreev Avatar answered Sep 28 '22 01:09

Alexey Andreev


Corutines are syntactic sugar around asyncronous procedures, or, better say, Actors, which are repeatable asynchronous procedures.

like image 33
Alexei Kaigorodov Avatar answered Sep 28 '22 02:09

Alexei Kaigorodov