Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test concurrent map read and map write

Tags:

go

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?

like image 777
Jachin Huang Avatar asked Jun 12 '26 07:06

Jachin Huang


1 Answers

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.

like image 153
Flimzy Avatar answered Jun 14 '26 08:06

Flimzy