Kotlin Coroutines: Difference between revisions
Jump to navigation
Jump to search
Line 2: | Line 2: | ||
I am doing this because of this graph | I am doing this because of this graph | ||
[[File:Moores law.png|700px]] | [[File:Moores law.png|700px]] | ||
<br> | |||
Previously there is fork/join for asynchronous but this code is far more complicated than it probably needs to be | Previously there is fork/join for asynchronous but this code is far more complicated than it probably needs to be | ||
<syntaxhighlight lang="kotlin"> | <syntaxhighlight lang="kotlin"> |
Revision as of 11:56, 27 December 2020
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
}
}