How to Solve Go Error: concurrent map iteration and map write

Pure dry goods.

Direct cause: problems caused by concurrent read/write of map. The source of your problem must be among the following reasons.

catalogue

Reason 1: abnormal loading and unlocking

Reason 2: adding unlock code looks normal

Reason 3: incomplete locking

Reason 4: the same lock is not added to the map


Reason 1: abnormal loading and unlocking

The code is not written rigorously, the lock is not unlocked, and a single closed loop is not formed
solution: if a closed loop is formed, there must be a solution

Reason 2: adding unlock code looks normal

In fact, the internal code of the lock is lonely. The map operation is not within the scope of the lock. The (read and write together) or the same map (same address) is used with the external code. The lock does not play a practical role

Solution: transfer the map data without using the old map, generate a new map between locking and unlocking,
transfer the data to the new map (or other data structures), and then return to the new map

Or

Just adjust the code position

Reason 3: incomplete locking

Only the goroutine that writes the map is unlocked, but the goroutine that reads the map is not or only goroutine reading map is unlocked, but goroutine writing is not or unlocked

Reason 4: the same lock is not added to the map

For example: for a map, there are two goroutines for reading the map and two goroutines for writing the map. The four are numbered 1,2,3,4. The first three use mu1 and the last one uses mu2, which will cause the error.

Warm tips:
the same lock can act on multiple maps, but the same map cannot have two locks.

Read More: