Skip to content

Instantly share code, notes, and snippets.

@stevegt
Created August 6, 2021 00:16
Show Gist options
  • Save stevegt/d23a53437ed2494362ad2b3eea067bf7 to your computer and use it in GitHub Desktop.
Save stevegt/d23a53437ed2494362ad2b3eea067bf7 to your computer and use it in GitHub Desktop.
contexts: simple cancel implementation using Go's context
package main
import (
"bufio"
"context"
"fmt"
"os"
"time"
)
func main() {
parentCtx := context.Background()
ctx, cancel := context.WithCancel(parentCtx)
// in := make(chan bool)
go func() {
reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter to cancel: ")
_, _ = reader.ReadString('\n')
// in <- true
// in <- true
cancel()
}()
go sleepAndTalk(ctx, 5*time.Second, "hello!")
go sleepAndTalk(ctx, 5*time.Second, "hello!")
time.Sleep(6 * time.Second)
}
func sleepAndTalk(ctx context.Context, t time.Duration, msg string) {
after := time.After(t)
select {
case <-after:
fmt.Println(msg)
case <-ctx.Done():
fmt.Println("got cancel")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment