Skip to content

Instantly share code, notes, and snippets.

@bartekpacia
Last active August 3, 2024 00:58
Show Gist options
  • Save bartekpacia/cda116a3cef9c520cd32dc108f4beec7 to your computer and use it in GitHub Desktop.
Save bartekpacia/cda116a3cef9c520cd32dc108f4beec7 to your computer and use it in GitHub Desktop.
Tour of Go (Concurrency) but in Kotlin Coroutines
import kotlinx.coroutines.*
suspend fun say(s: String) {
for (i in 1..5) {
delay(100L)
println(s)
}
}
fun main() = runBlocking {
launch { say("world") }
say("hello")
}
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
suspend fun sum(s: List<Int>, c: Channel<Int>) {
var sum = 0
for (v in s) {
sum += v
}
c.send(sum)
}
fun main() = runBlocking {
val s = listOf(7, 2, 8, -9, 4, 0)
val c = Channel<Int>()
launch { sum(s.subList(s.size / 2, s.size - 1), c) }
launch { sum(s.subList(0, s.size / 2), c) }
val x = c.receive()
val y = c.receive()
println("$x + $y = ${x + y}")
}
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
fun main() = runBlocking {
val c = Channel<Int>(capacity = 2)
c.send(1)
c.send(2)
println(c.receive())
println(c.receive())
}
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
suspend fun fibonacci(n: Int, c: Channel<Int>) {
var x = 0
var y = 1
for (i in 0..<n) {
c.send(x)
val oldX = x
x = y
y = oldX + y
}
c.close()
}
fun main() = runBlocking {
val cap = 10
val c = Channel<Int>(capacity = cap)
launch { fibonacci(cap, c) }
for (i in c) {
println(i)
}
}
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlinx.coroutines.selects.*
suspend fun fibonacci(c: Channel<Int>, quit: Channel<Int>) {
var x = 0
var y = 1
var running = true
while (running) {
select<Unit> {
c.onSend(x) { value ->
val oldX = x
x = y
y = oldX + y
}
quit.onReceive { value ->
println("quit")
running = false
}
}
}
}
fun main() = runBlocking {
val c = Channel<Int>()
val quit = Channel<Int>()
launch {
for (i in 0..<10) {
println(c.receive())
}
quit.send(0)
}
fibonacci(c, quit)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment