WorkPool(5个任务给3个goroutine工作)

package main

import (
    "fmt"
    "time"
)

var jobs chan int
var results chan int

func work(id int, jobs <-chan int, results chan<- int) {
    for i := range jobs {
        fmt.Printf("gorutine:%d;开始任务:%d;\n", id, i)
        time.Sleep(time.Second)
        fmt.Printf("gorutine:%d;结束任务:%d;\n", id, i)
        results <- i * 2
    }
}

//5个任务给3个gorutine工作
func main() {
    jobs := make(chan int, 100)
    results := make(chan int, 100)
    //开启3个Goroutine
    for w := 1; w <= 3; w++ {
        go work(w, jobs, results)
    }
    //5个任务
    for i := 1; i <= 5; i++ {
        jobs <- i
    }
    close(jobs)
    //输出结果
    for j := 1; j <= 5; j++ {
        <-results
    }
}

结果:

 

 

 

参考:https://www.youtube.com/watch?v=HmHgAGvV_yc&list=PLLPsLcbaFY20fG25TVsrCeAgXrBSrZDYU&index=87

 

posted @ 2021-06-25 14:57  蜗牛的礼物  阅读(33)  评论(0编辑  收藏  举报