workerPool _ golang

In this example we'll look at how to implement a worker pool using goroutines and channels

package main

import (
    "fmt"
    "time"
)

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

func main() {
    jobs := make(chan int, 100)
    result := make(chan int, 100)

    for w := 1; w <= 3; w++ {
        go worker(w, jobs, result)
    }

    for j := 1; j <= 9; j++ {
        jobs <- j
    }

    close(jobs)

    for a := 1; a <= 9; a++ {
        fmt.Println("<-result", <-result)
    }
}
worker 1 processing job 1
worker 2 processing job 2
worker 3 processing job 3
worker 1 processing job 4
worker 2 processing job 5
worker 3 processing job 6
<-result 2
<-result 4
<-result 6
worker 1 processing job 7
worker 2 processing job 8
worker 3 processing job 9
<-result 8
<-result 10
<-result 12
<-result 14
<-result 16
<-result 18

总结 :

  1 : ....

转载于:https://www.cnblogs.com/jackkiexu/p/4346936.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值