Switching contexts

Our first option is to use a different context for our update operation:

import kotlinx.coroutines.experimental.*

fun main(args: Array<String>) = runBlocking {
var counter = 0

val counterContext = newSingleThreadContext("CounterContext")

val time = measureTimeMillis {
repeatInParallel(1_000_000) {
withContext(counterContext) {
counter++
}
}
}
println("counter = $counter")
println("time = $time")
}

The withContext function executes a block in a specific coroutine context—in this case, a single-threaded one. Switching context is a powerful technique that lets us manipulate, in a fine-grained way, how our code runs.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.239.226