美文网首页
gobyexample-worker-pools

gobyexample-worker-pools

作者: bocsoft | 来源:发表于2018-11-05 17:27 被阅读0次

来源:https://github.com/xg-wang/gobyexample/tree/master/examples

//使用Go 协程和通道实现一个_工作池_
package main

import (
    "fmt"
    "time"
)

//多个并发实例中支持的任务。这些执行者将从`jobs`通道接收任务
//并且通过`results`发送对应的结果。我们让每个任务间隔1s来模仿一个耗时的任务
func worker(id int, jobs <-chan int, results chan<- int) {
    for j := range jobs {
        fmt.Println("worker", id, "processing job", j)
        time.Sleep(time.Second*2)
        results <- j * 2
    }
}

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

    //启动3个worker,初始是阻塞的,因为还没有传递任务
    for w := 1; w <= 3; w++ {
        go worker(w, jobs, results)//每批输出三个,随机选择job
    }

    //这里我们发送9个`jobs`,然后`close`这些通道来表示这些就是所有的任务了
    for j := 1; j <= 9; j++ {
        jobs <- j
    }
    close(jobs)//通知所有任务已完成

    //收集所有这些任务的返回值
    for a := 1; a <= 9; a++ {
        <-results
    }
}

输出结果:

worker 3 processing job 2
worker 1 processing job 1
worker 2 processing job 3
worker 3 processing job 4
worker 1 processing job 5
worker 2 processing job 6
worker 2 processing job 8
worker 1 processing job 7
worker 3 processing job 9

相关文章

网友评论

      本文标题:gobyexample-worker-pools

      本文链接:https://www.haomeiwen.com/subject/zjasxqtx.html