diff options
| -rw-r--r-- | main.go | 63 |
1 files changed, 42 insertions, 21 deletions
@@ -3,7 +3,7 @@ package main import ( "flag" "fmt" - "log" + "sync" "time" ) @@ -17,33 +17,54 @@ func main() { } func game(numSecs int) { - table := make(chan Ball) - go player("ping", table) - go player("pong", table) + var wg sync.WaitGroup + done := make(chan struct{}) + p0 := make(chan Ball) - table <- Ball{} + p1 := player(1, &wg, done, p0) + p2 := player(2, &wg, done, p1) + t := time.Tick(time.Duration(numSecs) * time.Second) - // Make the game last this long. - time.Sleep(time.Duration(numSecs) * time.Second) + p0 <- Ball{} - // Game over: grab the ball. - <-table +loop: + for b := range p2 { + select { + case p0 <- b: + case <-t: + break loop + } + } + + close(p0) + + wg.Wait() + fmt.Println("Done for now") } -func player(name string, table chan Ball) { - log.Printf("started player %s", name) +func player(id int, wg *sync.WaitGroup, done <-chan struct{}, input <-chan Ball) <-chan Ball { + out := make(chan Ball) - for { - ball := <-table - ball.hits++ - fmt.Println(name, ball.hits) + wg.Go(func() { + defer func() { + close(out) + fmt.Printf("(%d) finished\n", id) + }() - // Simulate some contact with the paddle. - time.Sleep(100 * time.Millisecond) + fmt.Printf("(%d) started\n", id) + loop: + for b := range input { + b.hits++ + fmt.Printf("(%d) %d\n", id, b.hits) + time.Sleep(100 * time.Millisecond) - table <- ball - } + select { + case out <- b: + case <-done: + break loop + } + } + }) - // FIXME: this is currently unreachable. - log.Printf("finished player %s", name) + return out } |
