Skip to content

Instantly share code, notes, and snippets.

@vikyd
Created November 28, 2018 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vikyd/08ecc86e57452b22e10007b201662b19 to your computer and use it in GitHub Desktop.
Save vikyd/08ecc86e57452b22e10007b201662b19 to your computer and use it in GitHub Desktop.
Golang context cancel multiple sleep
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithCancel(context.Background())
for i := 1; i <= 5; i++ {
go SleepCanBreak(ctx, 5, i)
}
fmt.Println("finish for")
time.Sleep(1 * time.Second)
cancel()
fmt.Println("cancel ed")
// wait all goroutine finish
time.Sleep(1 * time.Second)
fmt.Println("all finish")
}
func SleepCanBreak(ctx context.Context, sleep int, i int) (isBreak bool) {
select {
case <-ctx.Done():
isBreak = true
fmt.Printf("ctx.Done(), i: %d\n", i)
case <-time.After(time.Duration(sleep) * time.Second):
isBreak = false
fmt.Printf("sleep, i: %d\n", i)
}
return
}
// may print like:
// --------------------
// finish for
// cancel ed
// ctx.Done(), i: 1
// ctx.Done(), i: 5
// ctx.Done(), i: 3
// ctx.Done(), i: 4
// ctx.Done(), i: 2
// finish
// --------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment