main.go
· 439 B · Go
Sin formato
func doWork(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
default:
}
time.Sleep(1 * time.Second)
fmt.Println("doing work...")
}
}
func main() {
bgCtx := context.Background()
innerCtx, cancel := context.WithCancel(bgCtx)
go doWork(innerCtx) // call goroutine
time.Sleep(3 * time.Second) // do work in main
// well, if `doWork` is still not done, just cancel it
cancel()
}
1 | func doWork(ctx context.Context) { |
2 | for { |
3 | select { |
4 | case <-ctx.Done(): |
5 | return |
6 | default: |
7 | } |
8 | |
9 | time.Sleep(1 * time.Second) |
10 | fmt.Println("doing work...") |
11 | } |
12 | } |
13 | |
14 | func main() { |
15 | bgCtx := context.Background() |
16 | innerCtx, cancel := context.WithCancel(bgCtx) |
17 | |
18 | go doWork(innerCtx) // call goroutine |
19 | time.Sleep(3 * time.Second) // do work in main |
20 | |
21 | // well, if `doWork` is still not done, just cancel it |
22 | cancel() |
23 | } |
24 |