V
V
Vladimir Grabko2016-10-03 08:46:25
go
Vladimir Grabko, 2016-10-03 08:46:25

Is this code thread safe?

I know that I have already asked a bunch of times about this, but one figs I can not smoke thread safety.
The code:

import (
  "html/template"
  "sync"
)

var rw = &sync.RWMutex{}
var st = map[string]*template.Template{}

func Get(patch string) (*template.Template, bool) {
  rw.RLock()
  defer rw.RUnlock()
  q, w := st[patch]
  return q, w

}

func set(patch string, value *template.Template) {
  rw.Lock()
  defer rw.Unlock()
  st[patch] = value
}

The set function works in 1 thread before starting the web server, the Get function already "travels" through a bunch of routines. In fact, the map stores compiled html templates.
My thoughts:
map is thread safe
*template.Template is not safe because I work with a reference (what to do?)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nikita, 2016-10-03
@VGrabko

When you're working with map, even if you remove the pointer, nothing bad will happen.
But if you change the data under the pointer, then this is not safe in different threads. This requires one more mutex (or many per pointer), or in the Get method, make a copy and pass the copy pointer.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question