Concurrency 从不同的goroutine访问频道
我目前拥有以下代码:Concurrency 从不同的goroutine访问频道,concurrency,go,channel,goroutine,Concurrency,Go,Channel,Goroutine,我目前拥有以下代码: package main import ( "fmt" "math/rand" "time" ) var channel = make(chan []float32, 1) func main() { aMap := initMap() for key := range aMap { fmt.Print("the iteration number is: ", key) theSlice :=
package main
import (
"fmt"
"math/rand"
"time"
)
var channel = make(chan []float32, 1)
func main() {
aMap := initMap()
for key := range aMap {
fmt.Print("the iteration number is: ", key)
theSlice := aMap[key]
channel <- theSlice
go transition(channel)
time.Sleep(2 * time.Second)
}
}
func transition(channel chan []float32) {
newSlice := make([]float32,5)
newSlice = <- channel
fmt.Println(newSlice)
//need to retrieve the last element of the other slice and put it on this newSlice
}
func initMap() map[int][]float32 {
aMap := make(map[int][]float32)
for i := 0; i < 2; i++ {
aMap[i] = []float32{rand.Float32(), rand.Float32(), rand.Float32(), rand.Float32(), rand.Float32()}
}
return aMap
}
主程序包
进口(
“fmt”
“数学/兰德”
“时间”
)
var通道=制造(通道32,1)
func main(){
aMap:=initMap()
对于键:=范围aMap{
fmt.Print(“迭代编号为:”,键)
片:=aMap[key]
通道通道是双向的,并且是关于通信的,而不是共享内存。因此,也许不是发送整个切片,而是将每个切片中的最后一项沿通道向下发送,然后将第二个值以另一种方式发送回来
func main() {
...
// send only the last item
theSlice := aMap[key]
channel <- theSlice[len(theSlice)-1]
// waiting for the response
theSlice[len(theSlice)-1] = <- channel
}
func transition(channel chan []float32) {
newSlice := make([]float32,5)
channel <- newSlice[len(newSlice)-1]
newSlice[len(newSlice)-1] = <- channel
fmt.Println(newSlice)
}
我添加了一个编辑,澄清了我的问题。谢谢汉克斯,我给出的这个小例子很有意义。但是假设我们有两个以上的片段要处理,我不相信这种双向方法会起作用……顺便说一句:我必须承认我没有编译上面的内容,所以可能在某个地方有一个拼写错误。有一个很棒的演讲,涵盖了与cha的扇入扇出罗布·派克的nnels.talks.golang.org/2012/concurrency.slide。它有一些并发模式的好例子,非常值得研究。
var channel = make(chan float32, 1)