Golang Relativistic Card Lock

I have a recursive structure similar to a map that looks like this:

type RecurseTable struct {
    Table map[string]*RecurseTable
    // Other fields
    sync.RWMutex
}

If I am going to access this structure from several goroutines, how exactly can I block it? Let's say I read from a top-level card and write to a card of nested third-level cards. Is it fair to say that this will not cause any problems, since a change in the third level (and, therefore, indirect use through two pointers) should not affect the top-level map?

Similarly, if I have a goroutines pool that changes everything in a nested second-level structure, would it be that I only need to block every second-level map, because the top-level map contains only a pointer to a nested RecurseTable? Or is it that I have to block both the top-level map and the nested structure, because the structure can somehow be redistributed in memory, causing a change in the pointer stored as a value on the top-level map?

Another situation would be to add keys to the top level map while reading from the second level structure. Is it possible to assume that any reorganization of the top-level map due to the new key will not affect the location of the second-level structure in memory, and, therefore, there is no need to block the structure during reading?

, , goroutines . , , Golang .

+4
2

Go blogpost:

: , , . goroutines, - . - sync.RWMutex.

, ( ): , , , (.. ).

+2

, Get/Set, . :

type RecurseTable struct {
    table map[string]*RecurseTable
    // Other fields
    sync.RWMutex
}

func New() *RecurseTable {
    return &RecurseTable{
        table: make(map[string]*RecurseTable),
    }
}

func (r *RecurseTable) Get(key string) (*RecurseTable, bool) {
    r.RLock()
    defer r.RUnlock()
    return r.table[key]
}

func (r *RecurseTable) Set(key string, value *RecurseTable) {
    r.Lock()
    defer r.Unlock()
    r.table[key] = value
}  

, - , . .

+2

All Articles