【发布时间】:2020-03-12 04:02:30
【问题描述】:
package main
import (
"fmt"
"sync"
)
// 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
fmt.Printf("this is not getting printed")
fmt.Printf("PUT sent %d\n", value)
}
func main() {
var value int
var key string
wg := &sync.WaitGroup{}
hashMap := make(map[string](chan int), 100)
key = "xyz"
value = 100
for i := 0; i < 5; i++ {
wg.Add(1)
go put(hashMap, key, value, wg)
}
wg.Wait()
}
put 函数中的最后两个打印语句没有被打印出来,我正在尝试根据键将值放入映射中。
以及在这种情况下如何关闭 hashMap。
【问题讨论】:
-
查看可能重复的No output from goroutine,否则提供minimal reproducible example。
-
您确实在地图中初始化了频道,对吧?否则索引地图你会得到一个
nil频道,并在nil频道上发送永远阻塞,请参阅How does a non initialized channel behave? -
上述情况下如何初始化地图?我添加了可重现的代码
标签: go semaphore channel goroutine