1 /* 2 * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. 3 */ 4 5 // This file was automatically generated from shared-mutable-state-and-concurrency.md by Knit tool. Do not edit. 6 package kotlinx.coroutines.guide.exampleSync05 7 8 import kotlinx.coroutines.* 9 import kotlin.system.* 10 massiveRunnull11suspend fun massiveRun(action: suspend () -> Unit) { 12 val n = 100 // number of coroutines to launch 13 val k = 1000 // times an action is repeated by each coroutine 14 val time = measureTimeMillis { 15 coroutineScope { // scope for coroutines 16 repeat(n) { 17 launch { 18 repeat(k) { action() } 19 } 20 } 21 } 22 } 23 println("Completed ${n * k} actions in $time ms") 24 } 25 26 val counterContext = newSingleThreadContext("CounterContext") 27 var counter = 0 28 <lambda>null29fun main() = runBlocking { 30 // confine everything to a single-threaded context 31 withContext(counterContext) { 32 massiveRun { 33 counter++ 34 } 35 } 36 println("Counter = $counter") 37 } 38