cache2go icon indicating copy to clipboard operation
cache2go copied to clipboard

[bug]: delete operation in Foreach causes a deadlock

Open RealLiuSha opened this issue 5 years ago • 3 comments

test code:

package main

import (
	"fmt"
	"time"

	"github.com/muesli/cache2go"
)

func main() {
	store := cache2go.Cache("test")
	store.AddAboutToDeleteItemCallback(func(v *cache2go.CacheItem) {
		fmt.Println("delete:", v)
	})

	key := "test1"
	store.Add(key, time.Second*1800, "asdfasdfasd")
	fmt.Println("fitst delete:")
	store.Delete(key)

	store.Add(key, time.Second*1800, "asdfasdfasd")

	go func() {
		time.Sleep(time.Second * 2)
		fmt.Println("goroutine delete:")

		store.Foreach(func(key interface{}, v *cache2go.CacheItem) {
			fmt.Println("start")
			store.Delete(key)
			fmt.Println("end")
		})
	}()

	time.Sleep(time.Second * 10)
}

Foreach polls for all, while Rlock is released only after the Foreach execution completes, resulting in a deadlock when deleted in Foreach

RealLiuSha avatar Nov 25 '19 08:11 RealLiuSha

This error should be said that the user's use is not correct or the package design flaw itself?

pythonsite avatar Dec 25 '19 08:12 pythonsite

test code:

package main

import (
	"fmt"
	"time"

	"github.com/muesli/cache2go"
)

func main() {
	store := cache2go.Cache("test")
	store.AddAboutToDeleteItemCallback(func(v *cache2go.CacheItem) {
		fmt.Println("delete:", v)
	})

	key := "test1"
	store.Add(key, time.Second*1800, "asdfasdfasd")
	fmt.Println("fitst delete:")
	store.Delete(key)

	store.Add(key, time.Second*1800, "asdfasdfasd")

	go func() {
		time.Sleep(time.Second * 2)
		fmt.Println("goroutine delete:")

		store.Foreach(func(key interface{}, v *cache2go.CacheItem) {
			fmt.Println("start")
			store.Delete(key)
			fmt.Println("end")
		})
	}()

	time.Sleep(time.Second * 10)
}

Foreach polls for all, while Rlock is released only after the Foreach execution completes, resulting in a deadlock when deleted in Foreach

Yes,I try it and get a deadlock,trans func may not use Lock or RLock

leezhu avatar Aug 04 '20 15:08 leezhu

merge PR #48

lakshanwd avatar Oct 10 '20 22:10 lakshanwd