Skip to content

Instantly share code, notes, and snippets.

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