文件目录结构
.
├── cmd
│ ├── go.mod
│ └── main.go
└── worker
├── go.mod
└── worker.go
2 directories, 4 files
main.go 文件
package main
import (
"context"
"fmt"
"sync"
"time"
"worker"
)
var wg sync.WaitGroup
func main() {
ctx, cancel := context.WithCancel(context.Background())
wg.Add(1)
go worker.Worker(&wg, ctx)
// go worker.Worker(ctx)
time.Sleep(time.Second * 3)
cancel() // 通知子goroutine结束
wg.Wait()
fmt.Println("over")
}
worker.go 文件
package worker
import (
"context"
"fmt"
"sync"
"time"
)
// var wg sync.WaitGroup
// func Worker(ctx context.Context) {
func Worker(wg *sync.WaitGroup, ctx context.Context) {
LOOP:
for {
fmt.Println("worker")
time.Sleep(time.Second)
select {
case <-ctx.Done(): // 等待上级通知
break LOOP
default:
}
}
wg.Done()
}
执行cmd/main.go
go run main.go
worker
worker
worker
over