Created
November 28, 2018 08:06
-
-
Save vikyd/08ecc86e57452b22e10007b201662b19 to your computer and use it in GitHub Desktop.
Golang context cancel multiple sleep
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 ( | |
"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