Skip to content

Instantly share code, notes, and snippets.

@oops-oom
Last active February 9, 2018 07:20
Show Gist options
  • Select an option

  • Save oops-oom/87669c68723a1942100d3b776a35c95c to your computer and use it in GitHub Desktop.

Select an option

Save oops-oom/87669c68723a1942100d3b776a35c95c to your computer and use it in GitHub Desktop.
context 控制goroutine运行
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