package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, stopCh <-chan struct{}, wg *sync.WaitGroup) {
defer wg.Done()
defer fmt.Printf("Worker %d is exiting.\n", id)
for {
select {
case <-stopCh:
fmt.Printf("Worker %d received stop signal.\n", id)
return
case <-time.After(100 * time.Millisecond): // 假设worker每100毫秒执行一次工作
fmt.Printf("Worker %d is working.\n", id)
}
}
}
func main() {
const numWorkers = 100
stopCh := make(chan struct{})
var wg sync.WaitGroup
// 启动多个worker
for i := 0; i < numWorkers; i++ {
wg.Add(1) // 增加WaitGroup计数
go worker(i, stopCh, &wg)
}
// 模拟工作一段时间
time.Sleep(5 * time.Second)
// 发送停止信号
close(stopCh)
// 等待所有worker退出
wg.Wait()
fmt.Println("All workers have been stopped.")
}
go 通过channel通道控制多个协程的同时退出
最新推荐文章于 2024-08-22 05:53:17 发布