From 1d6b444d01762f90b18e455dbff84be3fded7288 Mon Sep 17 00:00:00 2001 From: Jian Han Date: Wed, 13 Dec 2017 22:46:39 +1000 Subject: [PATCH] added ping pong example --- concurrency/pingpong/main.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 concurrency/pingpong/main.go diff --git a/concurrency/pingpong/main.go b/concurrency/pingpong/main.go new file mode 100644 index 0000000..54eaece --- /dev/null +++ b/concurrency/pingpong/main.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "time" +) + +type Ball struct{ hits int } + +func main() { + table := make(chan *Ball) + go player("ping", table) + go player("pong", table) + table <- new(Ball) // game on; toss the ball + time.Sleep(1 * time.Second) + <-table // game over; grab the ball +} + +func player(name string, table chan *Ball) { + for { + ball := <-table + ball.hits++ + fmt.Println(name, ball.hits) + time.Sleep(100 * time.Millisecond) + table <- ball + } +}