V
V
Vladimir Grabko2016-06-23 19:57:59
go
Vladimir Grabko, 2016-06-23 19:57:59

Thread safety and pointers. Need blocking?

Googled.
Let's say there is some code that returns a pointer

func Db(name string) *DB{
  rw.RLock()
  _, ok :=  database[name]
  rw.RUnlock()
  if !ok {
    newDb(name)
    Db(name)
  }
  return database[name]
}

and a function for working with the structure
func (d *DB) Set(key string, value interface{}) bool {
  log.Println("cache.Set: ",key, " Value: ", value)
  d.RW.Lock()
  defer d.RW.Unlock()
  _, ok := d.Storage[key]
  if ok {
    log.Println("cache.Set: ",key, " exist")
    return false
  }
  d.Storage[key] = value
  return true
}

Are locks needed in the latter?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
evnuh, 2016-06-23
@VGrabko

Maps in Go are not thread safe, so yes, locks are needed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question