Last active
February 9, 2018 07:20
-
-
Save oops-oom/87669c68723a1942100d3b776a35c95c to your computer and use it in GitHub Desktop.
context 控制goroutine运行
This file contains hidden or 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" | |
| "sync" | |
| ) | |
| var wg sync.WaitGroup | |
| func main() { | |
| ctx := context.Background() | |
| ctx, cancel := context.WithCancel(ctx) | |
| wg.Add(1) | |
| go notmain(ctx) | |
| time.Sleep(1*time.Second) | |
| fmt.Println("start cancel ..") | |
| cancel() // cancel will not block | |
| fmt.Println("end cancel ..") | |
| wg.Wait() | |
| } | |
| func notmain(ctx context.Context) { | |
| for { | |
| select { | |
| case <- ctx.Done(): | |
| fmt.Println("Ending ...") | |
| wg.Done() | |
| return | |
| default: | |
| fmt.Println("Sleeping 10s ...") | |
| time.Sleep(10 * time.Second) | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment