【发布时间】:2019-12-11 22:13:47
【问题描述】:
我有两个函数,我想做的是在这两个函数之外有一个通道,第一个在 go 例程中运行并更新通道,然后第二个函数应该在通道中的项目到来时读取它们进去做点别的。当通道中的所有项目都完成后,go 例程应该优雅地退出
有人 ELI5 可以让我从同一个频道读取两个 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
上面的死锁是我不用粘贴大量代码就能解释的最简单的方法。
【问题讨论】:
-
您不需要将指针传递给通道。传递通道本身。
-
“因为 UpdatePeople 在单独的 go 例程中写入它” - UpdatePeople 不对频道做任何事情。这就是读操作阻塞主 goroutine 的原因(通道中什么都没有)
标签: go struct concurrency goroutine