gpt4 book ai didi

design-patterns - Go - 为什么调度 goroutine background workers 也需要自己的 goroutine?

转载 作者:IT王子 更新时间:2023-10-29 01:17:51 25 4
gpt4 key购买 nike

我正在研究 Go 的一些并发模式。我查看了使用 goroutine 和输入/输出 channel 实现后台工作程序,并注意到当我将新作业发送到接收 channel (本质上是将新作业排队)时,我必须在 goroutine 中进行,否则调度会被搞砸。含义:

这会崩溃:

for _, jobData := range(dataSet) {
input <- jobData
}

这有效:

go func() {
for _, jobData := range(dataSet) {
input <- jobData
}
}()

为了更具体一些,我玩了一些无意义的代码(here it is in go playground):

package main

import (
"log"
"runtime"
)

func doWork(data int) (result int) {
// ... some 'heavy' computation
result = data * data
return
}

// do the processing of the input and return
// results on the output channel
func Worker(input, output chan int) {
for data := range input {
output <- doWork(data)
}
}

func ScheduleWorkers() {

input, output := make(chan int), make(chan int)

for i := 0 ; i < runtime.NumCPU() ; i++ {
go Worker(input, output)
}

numJobs := 20

// THIS DOESN'T WORK
// and crashes the program
/*
for i := 0 ; i < numJobs ; i++ {
input <- i
}
*/

// THIS DOES
go func() {
for i := 0 ; i < numJobs ; i++ {
input <- i
}
}()

results := []int{}
for i := 0 ; i < numJobs ; i++ {
// read off results
result := <-output
results = append(results, result)
// do stuff...
}

log.Printf("Result: %#v\n", results)
}

func main() {
ScheduleWorkers()
}

我正在努力解决这个细微差别 - 感谢您的帮助。谢谢。

最佳答案

你的 ScheduleWorks函数在主 goroutine(即运行 main() 函数的 goroutine,程序在其中启动)中通过 input 发送一个值。 . Worker接收它,并通过 output 发送另一个值.但是没有人收到来自 output 的消息那时,程序无法继续,主 goroutine 将下一个值发送给另一个 Worker .

对每个 worker 重复这个推理。你有 runtime.NumCPU() worker ,这可能小于 numJobs .假设runtime.NumCPU() == 4 ,所以你有 4 个 worker 。最后,您成功发送了 4 个值,每个值都是一对一 Worker .因为没有人在阅读 output ,所有 Worker 都忙于尝试发送,因此他们无法通过 input 接受更多数据, 所以第五个 input <- i会挂。此时每个 goroutine 都在等待;这就是僵局。

enter image description here

您会注意到,如果您启动 20 个或更多 Worker 而不是 runtime.NumCPU() ,程序有效。那是因为主 goroutine 可以通过 input 发送它想要的一切。 ,因为有足够的 worker 来接收它们。

如果您不使用所有这些,而是​​将 input <- i在另一个 goroutine 中循环,就像在您的成功示例中一样,main goroutine(ScheduleWorks 在其中运行)可以继续并从 output 开始读取.因此,每次这个新的 goroutine 发送一个值时,worker 都会通过 output 发送另一个值。 ,主 goroutine 得到这个输出,worker 可以接收另一个值。没有人等待,程序成功。

enter image description here

关于design-patterns - Go - 为什么调度 goroutine background workers 也需要自己的 goroutine?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22606887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com