Sobes.tech
Junior — Senior

Synchronous access to a shared map in Go

livecode

Task condition

A global map map[string]int is declared in the program, and read and write operations are performed concurrently from different goroutines. The application crashes with the error fatal error: concurrent map read and map write. It is necessary to select an appropriate synchronization mechanism to eliminate this problem.

package main

import (
 "fmt"
 "sync"
 "time"
)

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

func main() {
 go read()
 time.Sleep(1 * time.Second)
 go write()
 time.Sleep(1 * time.Second)
}

func read() {
 for {
  mu.RLock()
  fmt.Println(m["a"])
  mu.RUnlock()
 }
}

func write() {
 for {
  mu.Lock()
  m["a"] = 2
  mu.Unlock()
 }
}