Go 采用 goroutine 和 channel 实现工作池

简介:

假设有一组任务需要异步处理且量很大,那我们需要同时开启多个 worker 以保证任务的处理速度而不会堵塞任务。其他语言,可能会需要开启多进程来完成,多进程的控制、IO 消耗等会是个需要注意的问题,而这些 Go 都能帮我们很轻易的解决。

大致的实现要点和流程:

  • 创建2个信道,messages 用于传送任务消息,result 用于接收消息处理结果
  • 创建3个 Worker 协程,用于接收和处理来自 messages 信道的任务消息,并将处理结果通过信道 result 返回
  • 通过信道 messages 发布10条任务
  • 通过信道 result 接收任务处理结果

示例代码:

package main

import (
    "fmt"
    "strconv"
    "math/rand"
    "time"
)

type Message struct {
    Id   int
    Name string
}

func main() {
    messages := make(chan Message, 100)
    result := make(chan error, 100)

    // 创建任务处理Worker
    for i := 0; i < 3; i ++ {
        go worker(i, messages, result)
    }

    total := 0
    // 发布任务
    for k := 1; k <= 10; k ++ {
        messages <- Message{Id: k, Name: "job" + strconv.Itoa(k)}
        total += 1
    }

    close(messages)

    // 接收任务处理结果
    for j := 1; j <= total; j ++ {
        res := <-result
        if res != nil {
            fmt.Println(res.Error())
        }
    }

    close(result)
}

func worker(worker int, msg <-chan Message, result chan<- error) {
    // 从通道 chan Message 中监听&接收新的任务
    for job := range msg {
        fmt.Println("worker:", worker, "msg: ", job.Id, ":", job.Name)

        // 模拟任务执行时间
        time.Sleep(time.Second * time.Duration(RandInt(1, 3)))

        // 通过通道返回执行结果
        result <- nil
    }
}

func RandInt(min, max int) int {
    rand.Seed(time.Now().UnixNano())
    return min + rand.Intn(max-min+1)
}

原文地址: https://shockerli.net/post/golang-worker-pools/

目录
相关文章
|
3月前
|
Go
go之channel关闭与广播
go之channel关闭与广播
|
11天前
|
Go 调度
Goroutine:Go语言的轻量级并发机制
【8月更文挑战第31天】
18 0
|
1月前
|
消息中间件 Kafka Go
从Go channel中批量读取数据
从Go channel中批量读取数据
|
1月前
|
缓存 并行计算 Go
go 语言中 channel 的简单介绍
go 语言中 channel 的简单介绍
|
2月前
|
缓存 编译器 Go
开发与运维线程问题之Go语言的goroutine基于线程模型实现如何解决
开发与运维线程问题之Go语言的goroutine基于线程模型实现如何解决
41 3
|
1月前
|
Go
在go中监听多个channel
在go中监听多个channel
|
3月前
|
存储 Go
Go 语言当中 CHANNEL 缓冲
Go 语言当中 CHANNEL 缓冲
|
3月前
|
存储 监控 Java
Go Goroutine 究竟可以开多少?(详细介绍)
Go Goroutine 究竟可以开多少?(详细介绍)
39 3
|
3月前
|
Go
go之channel任意任务完成、全部任务完成退出
go之channel任意任务完成、全部任务完成退出
|
3月前
|
Java Go 调度
Go语言并发(一)——goroutine与Waitgroup
Go语言并发(一)——goroutine与Waitgroup