Created
November 13, 2017 06:55
-
-
Save davibe/5c933a31f19bfbc92b728e3aab61463e to your computer and use it in GitHub Desktop.
Example of structured concurrency in Kotlin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import kotlinx.coroutines.experimental.* | |
import kotlinx.coroutines.experimental.channels.Channel | |
import java.util.* | |
/* | |
* Structured concurrency means that child co-routines should die when their father dies | |
* http://libdill.org//structured-concurrency.html | |
* | |
* In kotlin in order to have parent->child relationship you need to explicitly pass | |
* the coroutineContext to the child coroutine. | |
*/ | |
fun main(args: Array<String>) = runBlocking<Unit> { | |
println("Main: context ${coroutineContext}") | |
val father = launch(coroutineContext) { | |
println("Father: context ${coroutineContext}") | |
launch(coroutineContext) { | |
println("Child: context ${coroutineContext}") | |
do { | |
println("Child: is alive") | |
delay(1000) | |
} while (true) | |
} | |
// Father is not actually dead until `father.cancel()` because the child | |
// is keeping it alive. Here we could also use | |
// coroutineContext.cancel() or coroutineContext.cancelChildren() | |
} | |
delay(3000) | |
print("Main: killing father") | |
father.cancel() | |
delay(3000) | |
print("Main: is done") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output: