Is sync.Map the right tool for this use case? Or is a RW mutex lock better
Asked Answered
B

1

5

I am working on a golang project where tree nodes are stored in a map for quick access. Writes to the map will never happen concurrently (and for each key, they only happen once), but I would like to read concurrently with both reads/writes. I've been reading about both sync.Map and simply using RWMutex locks, but I am unsure which one is better for this use case (or if there is a 3rd party package that solves this problem). Does anybody have a recommendation on an approach/have any resources for reading up on the different options? Thank you!

Bolton answered 21/4, 2020 at 23:42 Comment(2)
The docs for sync.Map quite clearly explain when it's beneficial to use over a regular map with your own locking or coordination: The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys.Chalice
looks like sync.Map is the right tool for the job thenSelfwill
D
8

Start with using sync.Map. It's simpler than rolling your own, and will likely be faster.

The Map type is optimized for two common use cases: (1) when the entry for a given key is only ever written once but read many times, as in caches that only grow, or (2) when multiple goroutines read, write, and overwrite entries for disjoint sets of keys. In these two cases, use of a Map may significantly reduce lock contention compared to a Go map paired with a separate Mutex or RWMutex.

Case (1) in this quote (from the official docs of sync.Map) sound like exactly what you need.

If you end up being unhappy with the performance over time, benchmark it and replace the slow part with a faster solution (if possible).

Distort answered 22/4, 2020 at 0:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.