summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorShulhan <ms@kilabit.info>2018-09-03 23:07:34 +0700
committerShulhan <ms@kilabit.info>2018-09-03 23:07:34 +0700
commitb280835ed5fda0fd45cdaee4331d5eef256393e1 (patch)
tree63d3379639dbc52e56f98777b47baa83d3590a0b
parentea39d79730e5f5eefec3b2e8b1b401c74848c862 (diff)
downloadrescached-b280835ed5fda0fd45cdaee4331d5eef256393e1.tar.xz
Fix data race when pruning
-rw-r--r--cacheresponse.go11
-rw-r--r--cacheslist.go2
2 files changed, 12 insertions, 1 deletions
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
}