背景

在实际工作中,我们总会限制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
0
4
End task:0, job:1
End task:2, job:0
Start task:2, job:4
End task:2, job:4
End task:1, job:3
4
2

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2021-11-29
  • 2022-12-23
  • 2021-12-15
  • 2022-12-23
猜你喜欢
  • 2022-01-25
  • 2021-11-11
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
  • 2021-08-25
  • 2021-06-15
相关资源
相似解决方案