Skip to content

Instantly share code, notes, and snippets.

@fikr4n
Last active November 12, 2024 06:21
Show Gist options
  • Save fikr4n/d0edd0d5e76b22fa8fa2fab77d8f05b1 to your computer and use it in GitHub Desktop.
Save fikr4n/d0edd0d5e76b22fa8fa2fab77d8f05b1 to your computer and use it in GitHub Desktop.
A quick example of thread pool-like Kotlin coroutine
import kotlinx.coroutines.experimental.*
import kotlinx.coroutines.experimental.channels.*
class FixedPool(val workerCount: Int) {
val channel = Channel<Task>()
val jobs = mutableListOf<Job>()
init {
start() // start immediately
}
fun start() {
repeat(workerCount) { i ->
jobs.add(launch(CommonPool) { // or use your own coroutine context
for (task in channel) {
println("worker-$i starts ${task.name}")
task()
println("worker-$i finished ${task.name}")
}
})
}
}
fun execute(block: Task) {
launch(Unconfined) { // seems safe to use Unconfined
channel.send(block)
}
}
suspend fun join() {
for (j in jobs) j.join()
}
fun close() = channel.close()
}
class Task(val name: String, val time: Long) {
operator fun invoke() {
Thread.sleep(time) // block to simulate real operation
}
}
runBlocking {
val pool = FixedPool(2)
pool.execute(Task("A", 1000))
pool.execute(Task("B", 2500))
pool.execute(Task("C", 1000))
pool.execute(Task("D", 1000))
pool.execute(Task("E", 1000))
// We must wait; in long running app maybe not needed
pool.close()
pool.join()
}
// Example how to run on desktop:
// kotlinc-jvm -script coroutine-pool.kts -cp kotlinx-coroutines-core-0.22.2.jar -Xcoroutines=enable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment