1

I created a map that is safe for concurrent access, in each of the operations (or compound operations) I wrapped the operation with a lock.

func .. {
  mu.Lock()
  defer mu.Unlock()
  ..
}

Could I use goroutines for this also? Should I be using goroutines?

cool breeze
  • 4,461
  • 5
  • 38
  • 67
  • 1
    if all you need is a lock, what are you going to use goroutines for? – JimB Apr 19 '16 at 17:16
  • 3
    A lock is usually the best approach for synchronizing simple map access. – Charlie Tumahai Apr 19 '16 at 17:17
  • Also see http://stackoverflow.com/questions/34631561/should-goroutine-channel-based-mechanism-replace-a-concurrent-map, http://stackoverflow.com/questions/11063473/map-with-concurrent-access, http://stackoverflow.com/questions/36725098/creating-a-concurrent-safe-map-lock-or-goroutine, http://stackoverflow.com/questions/18192173/nice-go-idiomatic-way-of-using-a-shared-map, etc – JimB Apr 19 '16 at 17:19
  • To directly answer your question-- yes, that would work with goroutines. But you should really think about your design, and whether or not your design needs to include goroutines (since you asked if you *should* be using them), or if you can get away without using them. – william.taylor.09 Apr 19 '16 at 17:22

1 Answers1

1

This is no longer necessary in Go 1.9 and later. There is already a map implementation for concurrent use sync.Map.

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105