• GO worker pool


    背景

    在实际工作中,我们总会限制goroutine数量——worker pool模式,控制goroutine数量,避免goroutine泄露与膨胀

    示例

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func worker(w int, jobs <-chan int, results chan<- int) {
        for j := range jobs {
            fmt.Printf("Start task:%d, job:%d\n", w, j)
            time.Sleep(time.Second)
            results <- w * 2
            fmt.Printf("End task:%d, job:%d\n", w, j)
        }
    }
    
    func main() {
        jobs := make(chan int, 100)
        results := make(chan int, 100)
    
        // 开启3个goroutine
        for w := 0; w < 3; w++ {
            go worker(w, jobs, results)
        }
    
        // 跑5个任务
        for j := 0; j < 5; j++ {
            jobs <- j
        }
        close(jobs)
        
        //输出结果
        for a := 0; a < 5; a++ {
            tmp := <-results
            fmt.Println(tmp)
        }
    }

    执行

    2
    0
    4
    End task:0, job:1
    End task:2, job:0
    Start task:2, job:4
    End task:2, job:4
    End task:1, job:3
    4
    2

  • 相关阅读:
    jQuery中的事件
    Ajax跨域
    javascript的时间委托
    大型数据库优化技巧
    mysql数据库忘记密码时如何修改
    DAY69-nosql
    DAY68-redis
    DAY67-Memcached
    DAY65-apache的安装
    DAY63-centos介绍
  • 原文地址:https://www.cnblogs.com/kaituorensheng/p/15866063.html
Copyright © 2020-2023  润新知