Created
August 6, 2021 00:16
-
-
Save stevegt/d23a53437ed2494362ad2b3eea067bf7 to your computer and use it in GitHub Desktop.
contexts: simple cancel implementation using Go's 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 ( | |
"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