Sobes.tech
Junior — Senior

Safe concurrent access to the global map

livecode

Task condition

The program declares a global map map[string]int, which is accessed concurrently by multiple goroutines: one reads, another writes. This parallelism causes a panic fatal error: concurrent map read and map write. It is necessary to choose an appropriate synchronization mechanism to eliminate the race condition and ensure correct program operation.

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()
 }
}

What synchronization method (e.g., mutex, RWMutex, sync.Map, channels, etc.) should be used to solve the problem?