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.exampleSync07
7 
8 import kotlinx.coroutines.*
9 import kotlinx.coroutines.channels.*
10 import kotlin.system.*
11 
massiveRunnull12 suspend fun massiveRun(action: suspend () -> Unit) {
13     val n = 100  // number of coroutines to launch
14     val k = 1000 // times an action is repeated by each coroutine
15     val time = measureTimeMillis {
16         coroutineScope { // scope for coroutines
17             repeat(n) {
18                 launch {
19                     repeat(k) { action() }
20                 }
21             }
22         }
23     }
24     println("Completed ${n * k} actions in $time ms")
25 }
26 
27 // Message types for counterActor
28 sealed class CounterMsg
29 object IncCounter : CounterMsg() // one-way message to increment counter
30 class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg() // a request with reply
31 
32 // This function launches a new counter actor
<lambda>null33 fun CoroutineScope.counterActor() = actor<CounterMsg> {
34     var counter = 0 // actor state
35     for (msg in channel) { // iterate over incoming messages
36         when (msg) {
37             is IncCounter -> counter++
38             is GetCounter -> msg.response.complete(counter)
39         }
40     }
41 }
42 
<lambda>null43 fun main() = runBlocking<Unit> {
44     val counter = counterActor() // create the actor
45     withContext(Dispatchers.Default) {
46         massiveRun {
47             counter.send(IncCounter)
48         }
49     }
50     // send a message to get a counter value from an actor
51     val response = CompletableDeferred<Int>()
52     counter.send(GetCounter(response))
53     println("Counter = ${response.await()}")
54     counter.close() // shutdown the actor
55 }
56