Last active
December 15, 2021 06:50
-
-
Save Binary-Eater/2821f24a5a2a12eea6c3d9205ab90c08 to your computer and use it in GitHub Desktop.
Go ping pong with timeout context
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 ( | |
"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