Last active
July 20, 2016 14:10
-
-
Save caelifer/a04a1c419218648c5423 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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...") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Live code - https://play.golang.org/p/-S8Fy6SVrH
Output: