https://blog.csdn.net/qq_19283249/article/details/132019770
- 维护管理并kill掉所有的协程
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup, done chan bool) {
defer wg.Done() // 确保goroutine结束时从waitGroup中减去计数
for {
select {
case <-done:
fmt.Printf("Worker %d received done signal\n", id)
return // 当接收到done信号时,函数返回,wg计数减一
default:
fmt.Printf("Worker %d is doing some work\n", id)
time.Sleep(1 * time.Second)
}
}
}
func main() {
var wg sync.WaitGroup
done := make(chan bool)
// 启动多个goroutine
for i := 0; i < 10; i++ {
wg.Add(1)
go worker(i, &wg, done)
}
// 等待一段时间后通知所有goroutine退出
go func() {
time.Sleep(5 * time.Second)
fmt.Println("Main: Now closing all the workers")
close(done) // 关闭channel,通知所有worker退出
}()
// 等待所有goroutine结束
wg.Wait()
fmt.Println("Main: All workers are closed")
}
0 条评论