Fixes a concurrency issue with package path cache

The `chromedp-gen` tool, which makes use of the raw code, would
occassionally encounter a concurrent map write (on slow systems). This
adds a simple `sync.RWMutex` to the map causing problems.
This commit is contained in:
Kenneth Shaw
2018-12-18 09:40:51 -07:00
parent 60711f1a83
commit f60ef38230
+13 -5
View File
@@ -10,6 +10,7 @@ import (
"path/filepath"
"strconv"
"strings"
"sync"
)
func getPkgPath(fname string, isDir bool) (string, error) {
@@ -34,9 +35,12 @@ func getPkgPath(fname string, isDir bool) (string, error) {
return getPkgPathFromGOPATH(fname, isDir)
}
var (
goModPathCache = make(map[string]string)
)
var goModPathCache = struct {
paths map[string]string
sync.RWMutex
}{
paths: make(map[string]string),
}
// empty if no go.mod, GO111MODULE=off or go without go modules support
func goModPath(fname string, isDir bool) (string, error) {
@@ -45,13 +49,17 @@ func goModPath(fname string, isDir bool) (string, error) {
root = filepath.Dir(fname)
}
goModPath, ok := goModPathCache[root]
goModPathCache.RLock()
goModPath, ok := goModPathCache.paths[root]
goModPathCache.RUnlock()
if ok {
return goModPath, nil
}
defer func() {
goModPathCache[root] = goModPath
goModPathCache.Lock()
goModPathCache.paths[root] = goModPath
goModPathCache.Unlock()
}()
cmd := exec.Command("go", "env", "GOMOD")