有个银说面试中遇到了用channel 实现并发安全的map,写入时不阻塞,读取时设置超时的问题。
于是乎
package main
import (
"errors"
"time"
)
type concurrencyMap struct {
map_ map[int]int
cache chan struct{ key, value int }
}
func NewConcurrencyMap() *concurrencyMap {
mp := &concurrencyMap{
map_: make(map[int]int),
cache: make(chan struct{ key, value int }, 100),
}
go func() {
for val := range mp.cache {
mp.map_[val.key] = val.value
}
}()
return mp
}
func (c *concurrencyMap) Set(key, value int) {
go func() {
c.cache <- struct{ key, value int }{key, value}
}()
}
func (c *concurrencyMap) Get(timeout time.Duration, key int) (int, error) {
tc := time.NewTicker(timeout)
defer tc.Stop()
for {
select {
case <-tc.C:
return 0, errors.New("timeout")
default:
if value, ok := c.map_[key]; ok {
return value, nil
}
}
}
}