4

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?

Paul Hankin
  • 54,811
  • 11
  • 92
  • 118
Oleg Shevelev
  • 43
  • 1
  • 4
  • https://play.golang.org/p/5od76B-GVg – Oleg Shevelev Apr 20 '16 at 21:11
  • "competitive environment" = "concurrent environment"? "Die Konkurrenz" in German means "the competition" (and has nothing to do with concurrency), so I wonder if it's also confusing in other languages too. – Paul Hankin Apr 21 '16 at 00:12
  • Concurrent:) It was late at night when I translated from Russian to English:) Russian variant question: https://toster.ru/q/313102 – Oleg Shevelev Apr 22 '16 at 02:44

1 Answers1

6

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
JimB
  • 104,193
  • 13
  • 262
  • 255
  • I want to understand how to make the removal of the objects the most rational way and avoid unnecessary locks. GC for bad objects:) – Oleg Shevelev Apr 22 '16 at 02:50