course/context/context.go

53 lines
667 B
Go
Raw Permalink Normal View History

2024-07-29 00:25:13 +08:00
package main
import (
"context"
"fmt"
"sync"
"time"
)
var WG sync.WaitGroup
func f1(ctx context.Context) {
defer WG.Done()
go f2(ctx)
loop:
for {
fmt.Println("hello world")
time.Sleep(time.Millisecond * 500)
select {
case <-ctx.Done():
break loop
default:
}
}
}
func f2(ctx context.Context) {
defer WG.Done()
loop:
for {
fmt.Println("hello wangao")
time.Sleep(time.Millisecond * 500)
select {
case <-ctx.Done():
break loop
default:
}
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
WG.Add(1)
go f1(ctx)
time.Sleep(time.Second * 3)
//如何通知goroutine退出
cancel()
WG.Wait()
}