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

时间:2021-06-25 17:24:48   收藏:0   阅读:0
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

 

评论(0)
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!