blob: 84cbb3b2ce65ea845b69e17af646d4a5df86d97d [file] [log] [blame]
Roman Elizarovf16fd272017-02-07 11:26:00 +03001/*
Roman Elizarov1f74a2d2018-06-29 19:19:45 +03002 * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
Roman Elizarovf16fd272017-02-07 11:26:00 +03003 */
4
Roman Elizarovb7721cf2017-02-03 19:23:08 +03005// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
Roman Elizarova9687a32018-06-29 17:28:38 +03006package kotlinx.coroutines.experimental.guide.channel06
Roman Elizarovb7721cf2017-02-03 19:23:08 +03007
Roman Elizarov96695782017-10-01 10:48:15 -07008import kotlinx.coroutines.experimental.*
9import kotlinx.coroutines.experimental.channels.*
Roman Elizarovb7721cf2017-02-03 19:23:08 +030010
Roman Elizarov66f018c2017-09-29 21:39:03 +030011fun produceNumbers() = produce<Int> {
Roman Elizarovb7721cf2017-02-03 19:23:08 +030012 var x = 1 // start from 1
13 while (true) {
14 send(x++) // produce next
15 delay(100) // wait 0.1s
16 }
17}
18
Roman Elizarov66f018c2017-09-29 21:39:03 +030019fun launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch {
Roman Elizarov0dffcfd2018-06-29 18:51:52 +030020 for (msg in channel) {
21 println("Processor #$id received $msg")
Roman Elizarovec9384c2017-03-02 22:09:08 +030022 }
Roman Elizarovb7721cf2017-02-03 19:23:08 +030023}
24
25fun main(args: Array<String>) = runBlocking<Unit> {
26 val producer = produceNumbers()
27 repeat(5) { launchProcessor(it, producer) }
Roman Elizarov35d2c342017-07-20 14:54:39 +030028 delay(950)
Roman Elizarovb7721cf2017-02-03 19:23:08 +030029 producer.cancel() // cancel producer coroutine and thus kill them all
30}