← 返回 Golang 列表

Go 协程池与 Worker 模式

channel + worker pool 限制并发,防止 goroutine 泄漏与资源耗尽。

Worker Pool 示例

func worker(id int, jobs <-chan int, results chan-> int) {
  for j := range jobs {
    results <- j * 2
  }
}

func main() {
  jobs := make(chan int, 100)
  results := make(chan int, 100)

  for w := 1; w <= 3; w++ {
    go worker(w, jobs, results)
  }
}

优势