vaskir
06/16/2017, 7:03 PMclass ParallelBuilder<T> {
private val coroutines = ArrayList<Deferred<T>>()
fun prun(context: CoroutineContext = CommonPool,
start: CoroutineStart = CoroutineStart.DEFAULT,
block: suspend CoroutineScope.() -> T) {
coroutines.add(async(context, start, block))
}
suspend fun resume() = coroutines.map { it.await() }
}
inline suspend fun <R> parallel(crossinline builder: ParallelBuilder<R>.() -> Unit): List<R> {
val scope = ParallelBuilder<R>()
scope.builder()
return scope.resume()
}
fun main(args: Array<String>) = runBlocking {
val res = parallel<Int> {
prun {
println("1")
delay(1000)
println("1 done")
1
}
prun {
println("2")
delay(1000)
println("2 done")
2
}
prun {
println("3")
delay(1000)
println("3 done")
3
}
}
}
output
1
2
3
2 done
3 done
1 done
Result: [1, 2, 3]
I suspect there are a number of such functions already written 🙂 However, I didn't find one in the standard lib.