This is a creation in Article, where the information may have evolved or changed.
One,map concurrency and read-write problems
Fatal error:concurrent map Read and map write error if map is read and written simultaneously by multiple co-processes
The following code is easy to appear map concurrency Read and write problems
Func Main () {
c: = Make (Map[string]int)
Go func () {//Open a co-process to writeMap
For j: = 0; J < 1000000; J + + {
C[fmt. Sprintf ("%d", j)] = J
}
}()
Go func () {//Open a co-process readMap
For j: = 0; J < 1000000; J + + {
Fmt. Println (c[fmt. Sprintf ("%d", j)])
}
}()
Time. Sleep (time. SECOND*20)
}
Fatal Error:concurrent Map writes errors occur with multiple concurrent writes
The following code is prone to the problem of map concurrency write
Func Main () {
c: = Make (Map[string]int)
For I: = 0; I < 100; i++ {
Go func () {//Open -concurrent write of a processMap
For j: = 0; J < 1000000; J + + {
C[fmt. Sprintf ("%d", j)] = J
}
}()
}
Time. Sleep (time. SECOND*20)//Let the executionMainmain co-forming wait for function20s,Otherwise, the above concurrency operation will not be performed
}
Second, the cause of the problem
Because map is a reference type, even if a function is called, the parameter copy still points to the mapping m, so multiple goroutine concurrently write the same mapping m , the students who write too many threads know that, for shared variables, resources, concurrent read and write will produce competition, so the sharing of resources is compromised
Third, the solution
1, lock
(1) Universal Lock
Type Demo struct {
Data map[string]string
Lock sync. Mutex
}
Func (d Demo) Get (k string) string{
D.lock.lock ()
Defer D.lock.unlock ()
return D.data[k]
}
Func (d Demo) Set (K,v string) {
D.lock.lock ()
Defer D.lock.unlock ()
D.data[k]=v
}
(2) read/write lock
Type Demo struct {
Data map[string]string
Lock sync. Rwmutex
}
Func (d Demo) Get (k string) string{
D.lock.rlock ()
Defer D.lock.runlock ()
return D.data[k]
}
Func (d Demo) Set (K,v string) {
D.lock.lock ()
Defer D.lock.unlock ()
D.data[k]=v
}
2, the use of channel serialization processing