Skip to content

Instantly share code, notes, and snippets.

@Binary-Eater
Last active December 15, 2021 06:50
Show Gist options
  • Save Binary-Eater/2821f24a5a2a12eea6c3d9205ab90c08 to your computer and use it in GitHub Desktop.
Save Binary-Eater/2821f24a5a2a12eea6c3d9205ab90c08 to your computer and use it in GitHub Desktop.
Go ping pong with timeout context
package main
import (
"context"
"fmt"
"sync"
"time"
)
func pingPong(ctx context.Context, player string, wg *sync.WaitGroup, in <-chan struct{}, out chan<- struct{}) {
PingPongLoop:
for {
select {
case <-in:
fmt.Println(player)
select {
case out <- struct{}{}:
default:
}
case <-ctx.Done():
close(out)
fmt.Printf("Terminated %q\n", player)
break PingPongLoop
}
}
wg.Done()
}
func main() {
var wg sync.WaitGroup
wg.Add(2)
timeoutCtx, timeoutCancel := context.WithTimeout(context.Background(), time.Second)
defer timeoutCancel()
pingChan := make(chan struct{})
pongChan := make(chan struct{})
go pingPong(timeoutCtx, "ping", &wg, pingChan, pongChan)
go pingPong(timeoutCtx, "pong", &wg, pongChan, pingChan)
pingChan <- struct{}{}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment