Roman Elizarov | f16fd27 | 2017-02-07 11:26:00 +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 | f16fd27 | 2017-02-07 11:26:00 +0300 | [diff] [blame] | 3 | */ |
| 4 | |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 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.channel06 |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 7 | |
Roman Elizarov | 9669578 | 2017-10-01 10:48:15 -0700 | [diff] [blame] | 8 | import kotlinx.coroutines.experimental.* |
| 9 | import kotlinx.coroutines.experimental.channels.* |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 10 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 11 | fun produceNumbers() = produce<Int> { |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 12 | var x = 1 // start from 1 |
| 13 | while (true) { |
| 14 | send(x++) // produce next |
| 15 | delay(100) // wait 0.1s |
| 16 | } |
| 17 | } |
| 18 | |
Roman Elizarov | 66f018c | 2017-09-29 21:39:03 +0300 | [diff] [blame] | 19 | fun launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch { |
Roman Elizarov | 0dffcfd | 2018-06-29 18:51:52 +0300 | [diff] [blame] | 20 | for (msg in channel) { |
| 21 | println("Processor #$id received $msg") |
Roman Elizarov | ec9384c | 2017-03-02 22:09:08 +0300 | [diff] [blame] | 22 | } |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 23 | } |
| 24 | |
| 25 | fun main(args: Array<String>) = runBlocking<Unit> { |
| 26 | val producer = produceNumbers() |
| 27 | repeat(5) { launchProcessor(it, producer) } |
Roman Elizarov | 35d2c34 | 2017-07-20 14:54:39 +0300 | [diff] [blame] | 28 | delay(950) |
Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame] | 29 | producer.cancel() // cancel producer coroutine and thus kill them all |
| 30 | } |