From b280835ed5fda0fd45cdaee4331d5eef256393e1 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Mon, 3 Sep 2018 23:07:34 +0700 Subject: Fix data race when pruning --- cacheresponse.go | 11 +++++++++++ cacheslist.go | 2 +- 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/cacheresponse.go b/cacheresponse.go index c513f3f..4df96b8 100644 --- a/cacheresponse.go +++ b/cacheresponse.go @@ -6,6 +6,7 @@ package rescached import ( "container/list" + "sync" "time" "github.com/shuLhan/share/lib/dns" @@ -15,6 +16,7 @@ import ( // cacheResponse represent internal cache of DNS response. // type cacheResponse struct { + sync.Mutex // Time where cache last accessed. accessedAt int64 @@ -32,9 +34,18 @@ func newCacheResponse(res *dns.Response) *cacheResponse { } } +func (cres *cacheResponse) isExpired(expTime int64) bool { + cres.Lock() + yes := cres.accessedAt > expTime + cres.Unlock() + return yes +} + func (cres *cacheResponse) update(res *dns.Response) *dns.Response { + cres.Lock() oldres := cres.v cres.accessedAt = time.Now().Unix() cres.v = res + cres.Unlock() return oldres } diff --git a/cacheslist.go b/cacheslist.go index 2e251c1..f09f15e 100644 --- a/cacheslist.go +++ b/cacheslist.go @@ -65,7 +65,7 @@ func (cl *cachesList) prune() (lcres []*cacheResponse) { for el != nil { cres := el.Value.(*cacheResponse) - if cres.accessedAt > exp { + if cres.isExpired(exp) { break } -- cgit v1.3