我有两个功能,我想做的是在这两个功能之外有一个 channel ,第一个在 go 例程中运行并更新 channel ,然后第二个功能应该在 channel 中的项目进入并执行时读取它们别的东西。当 channel 中的所有项目都完成后,go 例程应该优雅地退出
有人可以 ELI5 如何让我从同一个 channel 读取两个 goroutine 吗?这甚至可能吗?
像下面这样的东西......
package main
import (
"fmt"
)
type Person struct {
index int
name string
age int
}
func UpdatePeople(psn *chan Person, grNo int) {
for i := 0; i < 5; i++ {
psn := Person{
index: 1,
name: "Shaun",
age: 23,
}
fmt.Printf("Person: %v --- GoRoutineNumber: %v\n", psn, grNo)
}
}
func WritePeople(psn *chan Person) {
for i := 0; i < 5; i++ {
psn := Person{
index: 1,
name: "Shaun",
age: 23,
}
fmt.Println("Writing People to DB", psn)
}
}
func main() {
//make channel of Person struct
psnChan := make(chan Person)
//I have a variable length in my program so lets say it's 6 in this case
for i := 0; i < 6; i++ {
/// I want to start a go routine here that writes to pointer of psnChan
go UpdatePeople(&psnChan, i)
}
// I then want to read in from the channel as UpdatePeople is writing to it in a separate go routine
for {
_, received := <-psnChan
if received == false {
fmt.Println("Break out of 2nd loop")
close(psnChan)
break
} else {
go WritePeople(&psnChan)
}
}
fmt.Println("Finished")
}
https://play.golang.org/p/ExJf3lY0VV8
上面的死锁但是是我可以解释的最简单的方法,而无需粘贴大量代码。
最佳答案
正如 Sergio 指出的那样,Main goroutine 正在阻塞,因为它正在等待从 psns channel 读取,但没有任何东西写入它。在编写 Go 时有一个很好的建议是只编写同步函数,另一个是负责创建 channel 的函数在关闭时进行控制。因此,考虑到这些,我已经对您写的内容进行了一些重组:https://play.golang.org/p/vicGN40pGVQ .该程序将慢慢找到 Person 对象,通过 channel 发送它们,并在执行过程中写入每个 Person。如果您的用例不同,请告诉我们:) 希望对您有所帮助。
关于golang 在两个 goroutine 之间同时传递结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59294918/