blob: 6e063053e48100edd706410dc3683677236c38be [file] [log] [blame]
Roman Elizarovb7721cf2017-02-03 19:23:08 +03001// This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit.
2package guide.channel.example06
3
4import kotlinx.coroutines.experimental.*
5import kotlinx.coroutines.experimental.channels.*
6
7fun produceNumbers() = buildChannel<Int>(CommonPool) {
8 var x = 1 // start from 1
9 while (true) {
10 send(x++) // produce next
11 delay(100) // wait 0.1s
12 }
13}
14
15fun launchProcessor(id: Int, channel: ReceiveChannel<Int>) = launch(CommonPool) {
16 while (true) {
17 val x = channel.receive()
18 println("Processor #$id received $x")
19 }
20}
21
22fun main(args: Array<String>) = runBlocking<Unit> {
23 val producer = produceNumbers()
24 repeat(5) { launchProcessor(it, producer) }
25 delay(1000)
26 producer.cancel() // cancel producer coroutine and thus kill them all
27}