GO worker pool

背景

在实际工作中,我们总会限制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

posted @ 2022-02-06 18:33  jihite  阅读(162)  评论(0编辑  收藏  举报