xref: /aosp_15_r20/external/kotlinx.coroutines/kotlinx-coroutines-core/jvm/test/guide/example-sync-04.kt (revision 7a7160fed73afa6648ef8aa100d4a336fe921d9a)
1 // This file was automatically generated from shared-mutable-state-and-concurrency.md by Knit tool. Do not edit.
2 package kotlinx.coroutines.guide.exampleSync04
3 
4 import kotlinx.coroutines.*
5 import kotlin.system.*
6 
massiveRunnull7 suspend fun massiveRun(action: suspend () -> Unit) {
8     val n = 100  // number of coroutines to launch
9     val k = 1000 // times an action is repeated by each coroutine
10     val time = measureTimeMillis {
11         coroutineScope { // scope for coroutines
12             repeat(n) {
13                 launch {
14                     repeat(k) { action() }
15                 }
16             }
17         }
18     }
19     println("Completed ${n * k} actions in $time ms")
20 }
21 
22 val counterContext = newSingleThreadContext("CounterContext")
23 var counter = 0
24 
<lambda>null25 fun main() = runBlocking {
26     withContext(Dispatchers.Default) {
27         massiveRun {
28             // confine each increment to a single-threaded context
29             withContext(counterContext) {
30                 counter++
31             }
32         }
33     }
34     println("Counter = $counter")
35 }
36