扇出模式 (Fan-Out Pattern)
扇出模式(Fan-Out Pattern)是一种并发编程模式,它将一个输入任务分发给多个并发处理器(也称为 worker),以提高处理速度。在 Go 语言中,可以使用 goroutine 和 channel 来实现扇出模式。
下面是一个简单的扇出模式示例,其中一个 goroutine 接收输入消息,将其发送到一个无缓冲 channel 中,然后多个 worker 从该 channel 中接收消息进行处理:
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, jobs <-chan int, results chan<- int) {
defer wg.Done()
for j := range jobs {
fmt.Println("worker", id, "processing job", j)
time.Sleep(time.Second)
results <- j * 2
}
}
var wg sync.WaitGroup
func main() {
// 创建两个 channel:一个用于发送任务,一个用于接收结果
jobs := make(chan int, 5)
results := make(chan int, 5)
// 启动三个 worker
wg.Add(3)
for w := 1; w <= 3; w++ {
go worker(w, jobs, results)
}
go func() {
wg.Wait()
close(results)
}()
// 发送五个任务
for j := 1; j <= 5; j++ {
jobs <- j
}
close(jobs)
// 输出结果
for a := 1; a <= 5; a++ {
<-results
}
}
在上面的代码中,我们首先定义了 worker
函数,该函数接收两个 channel:jobs
和 results
。jobs
用于接收任务,results
用于发送处理结果。在 worker
函数中,我们使用 for-range
循环从 jobs channel
中接收任务,处理完毕后将结果发送到 results channel
中。
在 main
函数中,我们首先创建了两个 channel:jobs
和 results
。然后启动了三个 worker
,并使用 jobs channel
发送了五个任务。我们在最后使用 for
循环从 results channel
中接收处理结果并输出。
运行上述代码,可以看到三个 worker
并发处理任务,可以提高任务处理速度。
推荐文章: