I'm really interested in the efficiency differences of these two
approaches.
They both work, and they both can/will be hidden behind an interface, so
it's just an implementation question.
I did a quick micro-benchmark on the mutex system, and .... I won't say
anything until I look deeper at my code.
I did find that RW mutexes are only slightly slower than regular mutexes. (
straight mutexes maybe 20% faster ). Thus only use RW mutexes if you really
think you're going to get a fair amount of contention. If it's a mostly
uncontended mutex, then of course use a straight mutex.
This is a standard C programmer thing, default to Mutex instead of RWMutex
because (especially in Linux's mutexes) RW locks tend to be a lot slower -
touch more state. In linux I think an RW is 2x to 3x slower in the
uncontended case.... of course Go doesn't use Linux's mutexes because
you're really communicating with the Go scheduler not the underlying thread
scheduler.
-brian
On Friday, December 5, 2014 12:16:10 PM UTC-8, Nick Craig-Wood wrote:On 05/12/14 19:36, ChrisLu wrote:In
https://golang.org/ref/mem , it talked about how to avoid
double-checked locking to initialize one variable, by using once.Do.
But how to efficiently and thread-safely initialize a multi-threaded map
entries?
For example: there is a highly concurrent map from a string to an object
pointer. Each map entry can only be created on the first map lookup.
map[string]*SomeObject m
string x
if _, ok := m[x]; !ok {
m[x] = &SomeObject{}
}
If you know any clean way to do this, please let me know.
Don't use any locking, use a channel where you send updates or read
requests to a go routine which manages the map.
This is the technique I used here
https://github.com/ncw/go-nflog-acctd/blob/master/main.go#L183Or as it says on the tin: Don't communicate by sharing memory; share
memory by communicating.
--
Nick Craig-Wood <ni...@craig-wood.com <javascript:>> --
http://www.craig-wood.com/nick --
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe@googlegroups.com.
For more options, visit
https://groups.google.com/d/optout.