Jachin Huang
Jachin Huang

Reputation: 31

test concurrent map read and map write

I am a newcomer to the go language. When I execute the code, I get the following error:
fatal error: concurrent map read and map write

func foo() {
    var m = map[string]int{"a": 1}
    var lock = sync.RWMutex{}

    go Read(m, lock)
    time.Sleep(1 * time.Second)
    go Write(m, lock)
    time.Sleep(1 * time.Minute)
}

func main() {
    foo()
}

func Read(m map[string]int, lock sync.RWMutex) {
    for {
        read(m, lock)
    }
}

func Write(m map[string]int, lock sync.RWMutex) {
    for {
        write(m, lock)
    }
}

func read(m map[string]int, lock sync.RWMutex) {
    lock.RLock()
    defer lock.RUnlock()
    _ = m["a"]
}

func write(m map[string]int, lock sync.RWMutex) {
    lock.Lock()
    defer lock.Unlock()
    m["b"] = 2
}

anyone can tell me why?

Upvotes: 3

Views: 769

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79594

You must pass a pointer to your sync.RWMutex value. Otherwise, you're making copies of the mutex every time you pass it to a new function, so no actual locking happens.

The go vet tool will detect this error for you. You should run go vet (and likely other linters) on all your code, to help catch such common errors. Related reading.

Upvotes: 9

Related Questions