英文:
How to make each worker work with Map Channel?
问题
我的代码片段:
主要工作器:
func Workergrab(m map[int][][]string, ch chan [][]string, wg *sync.WaitGroup) {
for y := 1993; y <= 2014; y++ {
ch <- m[y]
}
wg.Done()
}
工作器1:
fmt.Println(<-ch)
好的,这是我想要做的事情:
- > 主要工作器从 m[y] 中获取地图数据并将其发送到通道
- > 工作器1从通道中获取主要工作器同时根据 y 发送的数据
我已经尝试过上述方法,工作器1只显示了 m[1993] 的数据。搞砸了
我想使用地图通道,但不确定如何创建地图通道。
我觉得在通道的事情上搞砸了...,
我想知道如何创建一个 map[int][][]string
类型的通道,这样我的工作器1就可以从通道中获取每个 ID("1993"、"1994" 等)的数据了。
英文:
My Snippet code:
Main Worker:
func Workergrab(m map[int][][]string, ch chan [][]string, wg *sync.WaitGroup) {
for y := 1993; y <= 2014; y++ {
ch <- m[y]
}
wg.Done()
}
Worker1:
fmt.Println(<-ch)
Ok here was what i want to do
-> Main-Worker grabbing map data from m[y] and send it over to channel
-> Worker1 do get data from channel that main worker send at same time depend on y
I already tryed above, worker1 only show me m[1993] data. Messed
I was wondering using map channel, but not sure how make map channel.
I think messed up in channel thing...,
I wonder how i can make channel of
map[int][][]string so my worker1 will catch data from channel for each ID "1993", "1994" etc...
答案1
得分: 2
运行您的代码会出现“all goroutines are asleep - deadlock!”错误;这意味着两个goroutine要么已经结束,要么一直在写入/读取部分等待。
Workergrab
试图向ch
通道发送多个值,但Worker1
只打印一个ch
值并完成其工作。所以将Worker1
更改为以下内容可以解决问题:
func Worker1(ch chan [][]string) {
for {
fmt.Println(<-ch)
}
}
英文:
Running your code throw all goroutines are asleep - deadlock!
error; It means both of goroutines are ended or waited on writing/reading part forever.
Workergrab
tries to send more than one value to the ch
channel but Worker1
only prints one ch
value and finishes its work. So changing Worker1
as the following can solve the problem:
func Worker1(ch chan [][]string) {
for {
fmt.Println(<-ch)
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论