[Solved] Golang Error: fatal error: concurrent map writes

The specific codes are as follows:

package main

import (
	"fmt"
	"time"
)

var m = make(map[int]int, 10)

func solution(n int){
	res := 1
	for i:=1; i<=n; i++{
		res = res * i
	}
	m[n] = res
}

func main(){
	for i:=1; i<=200; i++{
		go solution(i)
	}
	time.Sleep(time.Second*10)
	for ind, val := range m{
		fmt.Printf("[%d] = %d \n", ind, val)
	}
}

The following error occurred:

fatal error: concurrent map writes
fatal error: concurrent map writes




runtime.mapassign_fast64(0x10b7760, 0xc00001e1b0, 0x12, 0x0)
        /usr/local/go/src/runtime/map_fast64.go:176 +0x325 fp=0xc000106fa0 sp=0xc000106f60 pc=0x1010bc5
main.solution(0x12)
        /Users/lcq/go/src/go_base/gochanneldemo/channeldemo.go:15 +0x65 fp=0xc000106fd8 sp=0xc000106fa0 pc=0x10a88a5
runtime.goexit()
        /usr/local/go/src/runtime/asm_amd64.s:1374 +0x1 fp=0xc000106fe0 sp=0xc000106fd8 pc=0x1062c41
created by main.main
        /Users/lcq/go/src/go_base/gochanneldemo/channeldemo.go:20 +0x58

The main reason is because map is not thread-safe, so it is not safe to use map in case of concurrency.
Solution.

    1. Add a lock
    2. Use sync.map
    3. Use a channel (multiple threads operating a channel is thread-safe)

Read More: