Kotlin Coroutines
Moores Law
I am doing this because of this graph
Previously there is fork/join for asynchronous but this code is far more complicated than it probably needs to be
override fun compute(): Long {
return if (high - low <= SEQUENTIAL_THRESHOLD) {
(low until high)
.map { array[it].toLong() }
.sum()
} else {
val mid = low + (high - low) / 2
val left = Sum(array, low, mid)
val right = Sum(array, mid, high)
left.fork()
val rightAns = right.compute()
val leftAns = left.join()
leftAns + rightAns
}
}
Using the suspend approach is far more easier to read
suspend fun compute(array: IntArray, low: Int, high: Int): Long {
// println("low: $low, high: $high on ${Thread.currentThread().name}")
return if (high - low <= SEQUENTIAL_THRESHOLD) {
(low until high)
.map { array[it].toLong() }
.sum()
} else {
val mid = low + (high - low) / 2
val left = async { compute(array, low, mid) }
val right = compute(array, mid, high)
return left.await() + right
}
}