在并发环境中从地图上删除是否安全? 在高朗

Do I put the lock before removing the item from map?

package main

import ( 
    "errors"
    "sync"
    "time"
)

type A struct {
    Error error
}

func (a *A) Job() {
//    ... more job
}

var l sync.RWMutex

func generate() {
    l.Lock()
    values["key1"] = A{}
    l.Unlock()
    l.Lock()
    values["key2"] = A{}
    values["key3"] = A{}
    l.Unlock()
 //   ...
    l.Lock()
    values["key1919"] = A{Error: errors.New("oh...")}
    l.Unlock()
 //   ...
    l.Lock()
    values["key99999999999"] = A{}
    l.Unlock()
}

var values map[string]A

func main() {
    values = make(map[string]A)
    go generate()

    for {
        l.RLock()
        for key, value := range values {
            if value.Error != nil {
                delete(values, key)    // it's safe? or you need to take a lock?
            } else {
                value.Job()
            }   
        }
        l.RUnlock()
        time.Sleep(10 * time.Second)
    }
}

Variants:

  1. delete in range without worrying

  2. add key in slice and separate range for to remove them

  3. l.RUnlock(); l.Lock(); delete(values, key); l.Unlock; l.RLock(); in range

  4. go l.delete(key) // gorutin splash

Which variant is the effective removal with lock/unlock?

Deleting from a map is considered a write operation, and must be serialized with all other reads and writes. If I understand your question correctly, then yes you need to either batch the deletes for later, or give up the read lock and take a write lock to complete the delete.

The runtime attempts to detect concurrent reads and writes, and will crash with one of:

fatal error: concurrent map writes
fatal error: concurrent map read and map write