Hi, if there is a map with key-value pair like (IP string, info struct{data string}
) and I need to frequently update the data
for each IP and from time to time I also need to add/remove IPs, so what is the better way for the concurrent control for the update of that Map except the RWLock? because for RWLock it will lock the whole map for each IP data update, thanks!
Maybe use sync.Map(sync package - sync - Go Packages).
sync.Map takes care of all that locking (or atomic operations) for you—so no manual locking needed
maybe you can try redis
It might be overkill, but you could use an in-memory caching solution such as:
You could also maybe take inspiration from their blog post about building it:
From the docs:
The Map type is specialized. Most code should use a plain Go map instead, with separate locking or coordination, for better type safety and to make it easier to maintain other invariants along with the map content.
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.
So in most cases using a Map with an RWMutex is probably the most straightforward and simplest solution. And only if the performance of this is not enough for you, you should search for a solution which fits your special case (and it might even be an in memory database)