zoukankan      html  css  js  c++  java
  • 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 : ....

  • 相关阅读:
    网站
    世上本无事,庸人自扰之
    mac系招聘BBS
    新浪微博语录帝摘录
    dwz jui
    cheap vps
    facebook的开发标准
    rails的一些插件
    租房宝
    在Z10上用3G
  • 原文地址:https://www.cnblogs.com/jackkiexu/p/4346936.html
Copyright © 2011-2022 走看看