func (t *Template) getTemplate(k string) (*template.Template, bool) {
t.templateMutex.RLock()
defer t.templateMutex.RUnlock()
if t.templateMap == nil { // Read done here in other go routine at the same time
t.templateMap = make(map[string]*template.Template) // WRITE DONE TO t.templateMap here without read lock
}
v, ok := t.templateMap[k]
return v, ok
}
func (t *Template) setTemplate(k string, v *template.Template) {
t.templateMutex.Lock()
defer t.templateMutex.Unlock()
t.templateMap[k] = v
}
Can this be fixed by a simple PR wrapping the assignment of the empty map in a Write Lock (mux.Lock) ?
E.g. like so:
func (t *Template) getTemplate(k string) (*template.Template, bool) {
t.templateMutex.RLock()
defer t.templateMutex.RUnlock()
if t.templateMap == nil {
t.templateMutex.Lock() // Lock prevents other routines from achieving a reader. Maybe add another check to see if it is still nil after getting the Write Lock?
defer t.templateMutex.Unlock()
t.templateMap = make(map[string]*template.Template)
}
v, ok := t.templateMap[k]
return v, ok
}
func (t *Template) setTemplate(k string, v *template.Template) {
t.templateMutex.Lock()
defer t.templateMutex.Unlock()
t.templateMap[k] = v
}
When running several tests concurrently, the go race detection results in an error in the template writer code:
Can this be fixed by a simple PR wrapping the assignment of the empty map in a Write Lock (
mux.Lock
) ?E.g. like so: