在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
背景在实际工作中,我们总会限制goroutine数量——worker pool模式,控制goroutine数量,避免goroutine泄露与膨胀 示例package main import ( "fmt" "time" ) func worker(w int, jobs <-chan int, results chan<- int) { for j := range jobs { fmt.Printf("Start task:%d, job:%d\n", w, j) time.Sleep(time.Second) results <- w * 2 fmt.Printf("End task:%d, job:%d\n", w, j) } } func main() { jobs := make(chan int, 100) results := make(chan int, 100) // 开启3个goroutine for w := 0; w < 3; w++ { go worker(w, jobs, results) } // 跑5个任务 for j := 0; j < 5; j++ { jobs <- j } close(jobs) //输出结果 for a := 0; a < 5; a++ { tmp := <-results fmt.Println(tmp) } } 执行 2 |
请发表评论