Roman Elizarov | b7721cf | 2017-02-03 19:23:08 +0300 | [diff] [blame^] | 1 | // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
| 2 | package guide.channel.example06 |
| 3 | |
| 4 | import kotlinx.coroutines.experimental.* |
| 5 | import kotlinx.coroutines.experimental.channels.* |
| 6 | |
| 7 | fun 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 | |
| 15 | fun 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 | |
| 22 | fun 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 | } |