course/context/context.go

53 lines
667 B
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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()
}