dgraph-io / ristretto

A high performance memory-bound Go cache
https://dgraph.io/blog/post/introducing-ristretto-high-perf-go-cache/
Apache License 2.0
5.54k stars 364 forks source link

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

Closed pthethanh closed 1 month ago

pthethanh commented 11 months ago

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()

github-actions[bot] commented 2 months ago

This issue has been stale for 60 days and will be closed automatically in 7 days. Comment to keep it open.