xref: /aosp_15_r20/external/kotlinx.coroutines/kotlinx-coroutines-core/jvm/test/guide/example-sync-06.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.exampleSync06
3 
4 import kotlinx.coroutines.*
5 import kotlinx.coroutines.sync.*
6 import kotlin.system.*
7 
massiveRunnull8 suspend fun massiveRun(action: suspend () -> Unit) {
9     val n = 100  // number of coroutines to launch
10     val k = 1000 // times an action is repeated by each coroutine
11     val time = measureTimeMillis {
12         coroutineScope { // scope for coroutines
13             repeat(n) {
14                 launch {
15                     repeat(k) { action() }
16                 }
17             }
18         }
19     }
20     println("Completed ${n * k} actions in $time ms")
21 }
22 
23 val mutex = Mutex()
24 var counter = 0
25 
<lambda>null26 fun main() = runBlocking {
27     withContext(Dispatchers.Default) {
28         massiveRun {
29             // protect each increment with lock
30             mutex.withLock {
31                 counter++
32             }
33         }
34     }
35     println("Counter = $counter")
36 }
37