Created
August 6, 2021 00:07
-
-
Save stevegt/9e92205c080311c3a53dd1181e8bad3b to your computer and use it in GitHub Desktop.
contexts: why Go's context is typically needed
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 ( | |
"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