Skip to content

Instantly share code, notes, and snippets.

@caelifer
Last active July 20, 2016 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save caelifer/a04a1c419218648c5423 to your computer and use it in GitHub Desktop.
Save caelifer/a04a1c419218648c5423 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"strconv"
"time"
)
type Ball int
func (b Ball) String() string {
return strconv.Itoa(int(b))
}
type Player string
func (p Player) Hit(table chan *Ball, b *Ball) {
*b++
fmt.Println(p, b)
table <- b
}
func play(p Player, table chan *Ball) {
for {
ball, ok := <-table
if !ok {
return
}
time.Sleep(time.Millisecond * 100)
p.Hit(table, ball)
}
}
func main() {
table := make(chan *Ball)
// Setup the game
go play("pong", table)
go play("ping", table)
// Start game by throwing in a ball
table <- new(Ball)
// Wait for some time
time.Sleep(time.Second)
// Finish the game by catching the ball
<-table
// Signal players to exit (clean-up)
close(table)
// Confirm all gorutines are done
time.Sleep(time.Millisecond)
panic("Check who is still running...")
}
@caelifer
Copy link
Author

caelifer commented Sep 3, 2015

Live code - https://play.golang.org/p/-S8Fy6SVrH

Output:

ping 1
pong 2
ping 3
pong 4
ping 5
pong 6
ping 7
pong 8
ping 9
pong 10
ping 11
pong 12
panic: Check who is still running...

goroutine 1 [running]:
panic(0x1283a0, 0x1040a1f0)
    /usr/local/go/src/runtime/panic.go:481 +0x700
main.main()
    /tmp/sandbox465543296/main.go:56 +0x200

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment