如何让每个工人与Map Channel一起工作?

huangapple go评论67阅读模式
英文:

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 &lt;= 2014; y++ {
		ch &lt;- m[y]
	}
	wg.Done()
}

Worker1:

fmt.Println(&lt;-ch)

Ok here was what i want to do

-&gt; Main-Worker grabbing map data from m[y] and send it over to channel
-&gt; 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(&lt;-ch)
	}
}

huangapple
  • 本文由 发表于 2022年1月3日 13:01:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/70561849.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定