Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 1 | /* |
Roman Elizarov | 1f74a2d | 2018-06-29 19:19:45 +0300 | [diff] [blame^] | 2 | * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
| 5 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
Roman Elizarov | a9687a3 | 2018-06-29 17:28:38 +0300 | [diff] [blame] | 6 | package kotlinx.coroutines.experimental.guide.sync01b |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 7 | |
| 8 | import kotlinx.coroutines.experimental.* |
Roman Elizarov | 9fe5f46 | 2018-02-21 19:05:52 +0300 | [diff] [blame] | 9 | import kotlin.system.* |
| 10 | import kotlin.coroutines.experimental.* |
Roman Elizarov | 43e9011 | 2017-05-10 11:25:20 +0300 | [diff] [blame] | 11 | |
| 12 | suspend fun massiveRun(context: CoroutineContext, action: suspend () -> Unit) { |
| 13 | val n = 1000 // number of coroutines to launch |
| 14 | val k = 1000 // times an action is repeated by each coroutine |
| 15 | val time = measureTimeMillis { |
| 16 | val jobs = List(n) { |
| 17 | launch(context) { |
| 18 | repeat(k) { action() } |
| 19 | } |
| 20 | } |
| 21 | jobs.forEach { it.join() } |
| 22 | } |
| 23 | println("Completed ${n * k} actions in $time ms") |
| 24 | } |
| 25 | |
| 26 | val mtContext = newFixedThreadPoolContext(2, "mtPool") // explicitly define context with two threads |
| 27 | var counter = 0 |
| 28 | |
| 29 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 30 | massiveRun(mtContext) { // use it instead of CommonPool in this sample and below |
| 31 | counter++ |
| 32 | } |
| 33 | println("Counter = $counter") |
| 34 | } |