幕布斯6054654

Job/Worker 模式是适用于此任务的常见 go 并发模式。多个 goroutine 可以从单个通道读取,在 CPU 内核之间分配大量工作,因此是工作程序的名称。在 Go 中,这种模式很容易实现——只需启动多个以通道为参数的 goroutine,然后将值发送到该通道——分发和多路复用将由 Go 运行时完成。package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "sync"&nbsp; &nbsp; "time")func worker(tasksCh <-chan int, wg *sync.WaitGroup) {&nbsp; &nbsp; defer wg.Done()&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; task, ok := <-tasksCh&nbsp; &nbsp; &nbsp; &nbsp; if !ok {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; d := time.Duration(task) * time.Millisecond&nbsp; &nbsp; &nbsp; &nbsp; time.Sleep(d)&nbsp; &nbsp; &nbsp; &nbsp; fmt.Println("processing task", task)&nbsp; &nbsp; }}func pool(wg *sync.WaitGroup, workers, tasks int) {&nbsp; &nbsp; tasksCh := make(chan int)&nbsp; &nbsp; for i := 0; i < workers; i++ {&nbsp; &nbsp; &nbsp; &nbsp; go worker(tasksCh, wg)&nbsp; &nbsp; }&nbsp; &nbsp; for i := 0; i < tasks; i++ {&nbsp; &nbsp; &nbsp; &nbsp; tasksCh <- i&nbsp; &nbsp; }&nbsp; &nbsp; close(tasksCh)}func main() {&nbsp; &nbsp; var wg sync.WaitGroup&nbsp; &nbsp; wg.Add(36)&nbsp; &nbsp; go pool(&wg, 36, 50)&nbsp; &nbsp; wg.Wait()}所有的 goroutine 并行运行,等待通道给它们工作。goroutine 几乎是一个接一个地立即接收它们的工作。这是一篇关于如何在 go 中每分钟处理 100 万个请求的精彩文章:http: //marcio.io/2015/07/handling-1-million-requests-per-minute-with-golang/
0
0