dgraph-io / ristretto

A high performance memory-bound Go cache

Home Page:https://dgraph.io/blog/post/introducing-ristretto-high-perf-go-cache/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[QUESTION]: Is there any way to implement an expired map counter with ristretto?

pthethanh opened this issue · comments

Question.

I wonder if there is any way that I could implement a counter with ristretto without wrap it around a sync.Mutex?
For now, if I want to implement a expired map counter with ristretto, I have to do this:

c, err := ristretto.NewCache(&ristretto.Config{
		MaxCost:     100,
		NumCounters: 1000,
		BufferItems: 64,
	})
	if err != nil {
		panic(err)
	}

	wg := sync.WaitGroup{}
	wg.Add(100)
	mux := new(sync.Mutex)
	for i := 0; i < 100; i++ {
		go func() {
			defer wg.Done()
			mux.Lock()
			v, ok := c.Get("key")
			if ok {
				v, _ := v.(int64)
				v++
				c.SetWithTTL("key", v, 1, 30*time.Second)
				c.Wait()
			} else {
				v := int64(1)
				c.SetWithTTL("key", v, 1, 30*time.Second)
				c.Wait()
			}
			mux.Unlock()
		}()
	}
	wg.Wait()
	fmt.Println(c.Get("key"))

I wonder what is the proper way to implement the counter correctly? I can replace int64 by atomic.Int64 but it also requires initial all the keys in advance.

So I wonder if atomic operations will be supported in the near future? like LoadOrStore(), CompareAndSwap(), CompareAndDelete()