A couple of comments. 

This is probably obvious, but I wanted to point out that matthe...'s code 
would require *all *access to the map to be synchronized using the mutex. 
It's a simple and effective solution. One downside to his code is that it 
holds the lock for the duration of the Copy(). This may be unacceptable 
depending on the size of the map and your latency requirements. If the map 
is very, very large, this could block a writer for an indeterminate amount 
of time. 

If your map met the requirements for sync.Map 
<https://golang.org/pkg/sync/#Map>, that struct contains a Range() method 
that allows for concurrent access. Depending on the requirements for the 
temporal strictness of the "snapshot", you could then use that function to 
create a copy without blocking other goroutines which might be attempting 
to write to the map. 

There are other, more complicated way that the Copy() lock time could be 
made constant, but they are significantly complicated. 



On Friday, January 26, 2018 at 9:56:38 PM UTC-5, matthe...@gmail.com wrote:
>
> Why not this?
>
> type StructMap map[string]*SomeStruct
>
> type SyncStructMap struct {
>     *sync.Mutex // maybe change to *sync.RWMutex if there are mixed 
> read/write synced operations
>     StructMap
> }
>
> func (a SyncStructMap) Copy() StructMap {
>     out := make(StructMap)
>     a.Lock()
>     for key, value := range a.StructMap {
>         out[key] = value
>     }
>     a.Unlock()
>     return out
> }
>
> // call with go keyword to make it execute concurrently
> func (a SyncStructMap) EncodeAndWrite() {
>     c := a.Copy()
>     // encode c then write to file
> }
>
> Matt
>
> On Friday, January 26, 2018 at 4:02:09 PM UTC-6, Tamás Gulácsi wrote:
>>
>> Do those *SomeStruct change during map serialization, or only the map 
>> (new keys / delete keys)?
>> If they do, you'll have to lock them too, not just the map access!
>>
>>

-- 
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