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.
-
- Add a lock
- Use sync.map
- Use a channel (multiple threads operating a channel is thread-safe)
Read More:
- [Go] Solve the fatal error: concurrent map writes map is not concurrently safe
- Golang Error: fatal error: concurrent map read and map writ
- How to Solve Go Error: concurrent map iteration and map write
- Hash_map is deprecated and will be REMOVED. Please use unordered_map.
- [Solved] Hystrix error: java.util.concurrent.TimeoutException: null
- package golang.org/x/net/XXX: unrecognized import path “golang.org/x/net/xxx“…
- Kafka Creates and Writes Logs Error [How to Solve]
- How to Solve Spark Writes Hudi Error
- How to Solve golang test Error: # command-line-arguments [command-line-arguments.test]
- Golang Error: go get github/xxx [How to Fix]
- How to Solve spark Writes Files to odps Error
- [Go] Solve panic: runtime error: invalid memory address or nil pointer dereference in golang
- [GO] The entry file under the main package in golang calls other go file functions and appears undefined
- [Solved] Golang Error: main.go:5:2: package go_code/chapter10/factory/model is not in GOROOT
- [Solved] cocopod Error: failed: undefined method `map‘ for nil:NilClass
- [Solved] IP Core Map Compile Error: Buffers of the same direction cannot beplaced in series.
- [Solved] Searching for inspections failed: undefined method `map‘ for nil:NilClass“
- How to Solve Error: IncompleteElementException: Could not find result map…
- How to Solve Cordova integrates Gaode Map key error
- How to Solve Error: Missing type map configuration or unsupported mapping