| /* |
| * Copyright 2016-2017 JetBrains s.r.o. |
| * |
| * Licensed under the Apache License, Version 2.0 (the "License"); |
| * you may not use this file except in compliance with the License. |
| * You may obtain a copy of the License at |
| * |
| * http://www.apache.org/licenses/LICENSE-2.0 |
| * |
| * Unless required by applicable law or agreed to in writing, software |
| * distributed under the License is distributed on an "AS IS" BASIS, |
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| * See the License for the specific language governing permissions and |
| * limitations under the License. |
| */ |
| |
| // This file was automatically generated from coroutines-guide.md by Knit tool. Do not edit. |
| package kotlinx.coroutines.experimental.guide.channel09 |
| |
| import kotlinx.coroutines.experimental.* |
| import kotlinx.coroutines.experimental.channels.* |
| import kotlin.coroutines.experimental.* |
| |
| data class Ball(var hits: Int) |
| |
| fun main(args: Array<String>) = runBlocking<Unit> { |
| val table = Channel<Ball>() // a shared table |
| launch(coroutineContext) { player("ping", table) } |
| launch(coroutineContext) { player("pong", table) } |
| table.send(Ball(0)) // serve the ball |
| delay(1000) // delay 1 second |
| coroutineContext.cancelChildren() // game over, cancel them |
| } |
| |
| suspend fun player(name: String, table: Channel<Ball>) { |
| for (ball in table) { // receive the ball in a loop |
| ball.hits++ |
| println("$name $ball") |
| delay(300) // wait a bit |
| table.send(ball) // send the ball back |
| } |
| } |