53 lines
667 B
Go
53 lines
667 B
Go
|
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()
|
|||
|
|
|||
|
}
|