From 13f110e5c84469f8eb2be750b2a3b7ef71625afd Mon Sep 17 00:00:00 2001 From: Sergey Matveev Date: Sat, 7 Oct 2023 20:14:22 +0300 Subject: [PATCH] Protect concurrent map r/w --- ifchange.go | 2 +- tgt.go | 21 +++++++++++++-------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/ifchange.go b/ifchange.go index a55120e..374adcf 100644 --- a/ifchange.go +++ b/ifchange.go @@ -80,7 +80,7 @@ func buildDependants(tgts []*Tgt) map[string]*Tgt { } } } - TgtCache = nil + TgtCache = make(map[string]*Tgt) IfchangeCache = nil if len(seen) == 0 { return seen diff --git a/tgt.go b/tgt.go index 3fa14a0..1cba1e6 100644 --- a/tgt.go +++ b/tgt.go @@ -3,9 +3,13 @@ package main import ( "path" "path/filepath" + "sync" ) -var TgtCache = make(map[string]*Tgt) +var ( + TgtCache = make(map[string]*Tgt) + TgtCacheM sync.RWMutex +) func mustAbs(pth string) string { pth, err := filepath.Abs(pth) @@ -43,10 +47,11 @@ type Tgt struct { func NewTgt(tgt string) *Tgt { a := mustAbs(tgt) - if TgtCache != nil { - if t := TgtCache[a]; t != nil { - return t - } + TgtCacheM.RLock() + cached := TgtCache[a] + TgtCacheM.RUnlock() + if cached != nil { + return cached } h, t := pathSplit(a) res := Tgt{ @@ -54,9 +59,9 @@ func NewTgt(tgt string) *Tgt { rel: mustRel(Cwd, a), dep: path.Join(h, RedoDir, t+DepSuffix), } - if TgtCache != nil { - TgtCache[a] = &res - } + TgtCacheM.Lock() + TgtCache[a] = &res + TgtCacheM.Unlock() return &res } -- 2.44.0