Go maps fails the concurency test


When I run the following code:

import (
func TestConcurrency(t *testing.T) {
var mutex sync.RWMutex
dictionary := make(map[interface{}]interface{})
go func() {
    var value interface{}
    for {
        go func() {
            dictionary["Key"] = ""

        go func() {
            value = dictionary["Key"]


using :

go test -race fileName.go

It results in:

Found 1 data race(s)

How can I solve this?

I have many concurrent writes and reads.


If you look at the error presented by the race detector, you would see that it reported concurrent writes on the value = dictionary["Key"] line, meaning the race being detected is on value, not dictionary.

You are concurrently accessing 2 variables, dictionary and value. You can’t use the read lock to protect reads on the map, and writes to the value variable. You either need a second mutex, or you need to always use mutex.Lock to serialize access to both variables.

Answered By – JimB

Answer Checked By – Clifford M. (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.