Channel Synchronization in Kotlin
In Kotlin, we can use coroutines to achieve similar functionality to Go’s goroutines for concurrent execution. Here’s an example of using a channel (implemented as a Channel
from kotlinx.coroutines) to synchronize execution across coroutines:
To run this program:
In this Kotlin version:
We use
suspend fun
to define ourworker
function, which can be suspended and resumed.Instead of Go’s
time.Sleep
, we use Kotlin’sdelay
function for suspending the coroutine.We create a
Channel<Boolean>
instead of a Go channel.The
go
keyword is replaced by launching a new coroutine withlaunch { ... }
.The main function is wrapped in
runBlocking
, which creates a coroutine and blocks the current thread until all launched coroutines complete.We use
done.send(true)
to send a value to the channel anddone.receive()
to receive from it.
If you removed the done.receive()
line from this program, the program would exit before the worker
even started, similar to the Go version.
Note: This example requires the kotlinx-coroutines-core
library. Make sure to include it in your project dependencies.