3 回答

TA貢獻1735條經(jīng)驗 獲得超5個贊
您需要創(chuàng)建一個頻道,例如
hashMap[key] = make(chan int)
由于您沒有從通道中讀取數(shù)據(jù),因此需要緩沖通道才能使其工作:
key := "xyz" hashMap[key] = make(chan int, 5)
嘗試以下代碼:
func put(hashMap map[string](chan int), key string, value int, wg *sync.WaitGroup) {
hashMap[key] <- value
fmt.Printf("PUT sent %d\n", value)
wg.Done()
}
func main() {
var wg sync.WaitGroup
hashMap := map[string]chan int{}
key := "xyz"
hashMap[key] = make(chan int, 5)
for i := 0; i < 5; i++ {
wg.Add(1)
go put(hashMap, key, 100, &wg)
}
wg.Wait()
}
輸出:
PUT sent 100
PUT sent 100
PUT sent 100
PUT sent 100
PUT sent 100

TA貢獻1878條經(jīng)驗 獲得超4個贊
我解決該問題的解決方案是:
// PUT function
func put(hashMap map[string](chan int), key string, value int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("this is getting printed")
hashMap[key] <- value // <-- nil problem
fmt.Printf("this is not getting printed")
fmt.Printf("PUT sent %d\n", value)
}
在函數(shù)的這行代碼中hashMap[key] <- value,put它不能接受,value因為它chan int是nil在參數(shù)中定義的put (hashMap map[string](chan int)。
// PUT function
func put(hashMap map[string](chan int), cval chan int, key string, value int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Println("this is getting printed")
cval <- value // put the value in chan int (cval) which is initialized
hashMap[key] = cval // set the cval(chan int) to hashMap with key
fmt.Println("this is not getting printed")
fmt.Printf("PUT sent %s %d\n", key, value)
}
func main() {
var value int
wg := &sync.WaitGroup{}
cval := make(chan int,100)
hashMap := make(map[string](chan int), 100)
value = 100
for i := 0; i < 5; i++ {
wg.Add(1)
go put(hashMap, cval, fmt.Sprintf("key%d",i), value, wg)
}
wg.Wait()
/* uncomment to test cval
close(cval)
fmt.Println("Result:",<-hashMap["key2"])
fmt.Println("Result:",<-hashMap["key1"])
cval <- 88 // cannot send value to a close channel
hashMap["key34"] = cval
fmt.Println("Result:",<-hashMap["key1"])
*/
}
在我的代碼示例中。我將cval緩沖通道 100 初始化為相同大小,hashMap并將 cval 作為put函數(shù)中的值傳遞。您只能關(guān)閉cval而不是 hashMap 本身。

TA貢獻1797條經(jīng)驗 獲得超6個贊
另外,您的代碼可以簡化為這樣。為什么要傳遞不必要的參數(shù)!一項額外的修改是我采用了不同的值,以使您更清楚地理解這個概念。
package main
import (
"log"
"sync"
)
func put(hash chan int, wg *sync.WaitGroup) {
defer wg.Done()
log.Println("Put sent: ", <-hash)
}
func main() {
hashMap := map[string]chan int{}
key := "xyz"
var wg sync.WaitGroup
hashMap[key] = make(chan int, 5)
for i := 0; i < 5; i++ {
value := i
wg.Add(1)
go func(val int) {
hashMap[key] <- val
put(hashMap[key], &wg)
}(value)
}
wg.Wait()
}
- 3 回答
- 0 關(guān)注
- 198 瀏覽
添加回答
舉報