等待映射中的值在 Go 中可用

等待映射中的值在 go 中可用

问题内容

我有一个程序,基本上有三种情况 - 设置键的值,获取值(如果存在),或者等到给定键的值可用。我最初的想法 - 创建一个带有 map[string]interface{} 的新类型 - 其中存储“持久”值。除此之外,为了等待一个值,我计划使用 map[string](chan struct{})。当调用 set() 方法时,我会写入该通道,任何等待它的人都会知道该值在那里。

我事先不知道密钥 - 它们是随机的。我不确定如何正确实现 wait() 方法。

type Map struct { sync.Mutex m map[string]interface{} wait map[string]chan (struct{}) } func (m *Map) Set(key string, value interface{}) { m.ensureWaitChan(key) m.Lock() defer m.Unlock() m.m[key] = value // Signal to all waiting. m.wait[key] 登录后复制