type SafeCounter struct {
mu sync.Mutex
value map[string]int
}
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
defer c.mu.Unlock()
c.value[key]++
}
func (c *SafeCounter) Get(key string) int {
c.mu.Lock()
defer c.mu.Unlock()
return c.value[key]
}
type ReadOnlyFrequent struct {
mu sync.RWMutex
data map[string]interface{}
}
func (r *ReadOnlyFrequent) Get(key string) interface{} {
r.mu.RLock()
defer r.mu.RUnlock()
return r.data[key]
}
func (r *ReadOnlyFrequent) Set(key string, value interface{}) {
r.mu.Lock()
defer r.mu.Unlock()
r.data[key] = value
}
type Command struct {
key string
value int
op string // "inc", "get"
resp chan int
}
type Counter struct {
data map[string]int
cmd chan Command
}
func NewCounter() *Counter {
c := &Counter{
data: make(map[string]int),
cmd: make(chan Command),
}
go c.run()
return c
}
func (c *Counter) run() {
for cmd := range c.cmd {
switch cmd.op {
case "inc":
c.data[cmd.key]++
case "get":
cmd.resp <- c.data[cmd.key]
}
}
}
func (c *Counter) Inc(key string) {
c.cmd <- Command{key: key, op: "inc"}
}
func (c *Counter) Get(key string) int {
resp := make(chan int)
c.cmd <- Command{key: key, op: "get", resp: resp}
return <-resp
}
type AtomicCounter struct {
count int64
}
func (a *AtomicCounter) Inc() {
atomic.AddInt64(&a.count, 1)
}
func (a *AtomicCounter) Load() int64 {
return atomic.LoadInt64(&a.count)
}
