Thanks, snmed,

I was looking at LoadOrStore, but I was assuming that any func would be 
executed in any case.

A more illustrative running sample of your first example:

https://play.golang.org/p/vjlVu1GnUQ

Thanks again!

bep

fredag 1. september 2017 08.24.10 UTC+2 skrev snmed følgende:
>
> Hi 
>
> Here are two examples how to achieve it: 
> https://play.golang.org/p/wAtyGMSw6g or 
> https://play.golang.org/p/EZWZUOpuwb
>
> First example: In best cases it executes the creator function once and 
> returns always the stored item, in bad cases it executes the creator 
> function multiple times but returns always the first
> stored item. 
>
> Second example uses a lock to create and store the item.
>
> If the creator function is expensive, then I would use the latter example 
> otherwise the first.
>
> Cheers snmed
>
>
> Am Freitag, 1. September 2017 00:18:35 UTC+2 schrieb bep:
>>
>> sync.Map in Go 1.9 is a little low on examples/doc in the wild, so I 
>> thought I should ask here.
>>
>> The new type is promoted as a replacement for  RWMutex in mostly read use 
>> cases with stable keys. I assume that a typical in memory cache would fit 
>> that description.
>>
>> With RWMutex, if the cost of creating the cache item is high, I would 
>> maybe do something ala:
>>
>> mu.RLock()
>> // Check cache
>> mu.RUnclock()
>>
>> // Return if found
>>
>> // If Not found:
>> mu.Lock()
>> defer mu.Unlock()
>> // Double check cache, return if found
>> // Create item and put in cache
>>
>>
>>
>>
>> I don't see how the above can be written with a sync.Map without adding a 
>> mutex.
>>
>> bep
>>
>

-- 
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+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to