Skip to content

工作池

https://gobyexample-cn.github.io/worker-pools

go
package main

import (
    "fmt"
    "time"
)

func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("worker", id, "started  job", j)
        time.Sleep(time.Second)
        fmt.Println("worker", id, "finished job", j)
        results <- j * 2
    }
}

func main() {

    const numJobs = 5
    jobs := make(chan int, numJobs)
    results := make(chan int, numJobs)

    for w := 1; w <= 3; w++ {
        // 创建了 3 个 worker
        go worker(w, jobs, results)
    }

    // 派发任务 大于 numJobs 会卡住
    // result 会写不进去,从而 goroutine 泄漏
    for j := 1; j <= numJobs; j++ {
        jobs <- j
    }
    close(jobs)

    for a := 1; a <= numJobs; a++ {
       result:= <-results

    }
}

注意

go
for a := 1; a <= numJobs; a++ {
    <-results
}

并不需要 close,但是换成 range results 就必须 close ,否则会卡住