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:
delete in range without worrying
add key in slice and separate range for to remove them
l.RUnlock(); l.Lock(); delete(values, key); l.Unlock; l.RLock(); in range
go l.delete(key) // gorutin splash
Which variant is the effective removal with lock/unlock?