This is a creation in Article, where the information may have evolved or changed.
Go official should be more recommended to use Chan
Https://github.com/golang/go/wiki/MutexOrChannel
The following code is used to test performance-not to make sure that the idea is correct.
PackageMainImport("FMT" "Sync" "Time")typeOpstruct{KeyintValint}varLock sync. MutexvarM1Map[int]intvarM2Map[int]intvarMaxint=50000funcUpdate_map_by_mutex (iint) {lock. Lock () m1[i] = iif Len(m1) = = max {fmt. Printf ("%s Mutex finish\n", time. Now ())} lock. Unlock ()}varChChanOpfuncUpdate_map_by_chan (iint) {ch <-op{key:i, Val:i}}funcWait_for_chan (MMap[int]int) { for{Select{ CaseOP: = <-ch:m[op.key] = Op.valif Len(m2) = = max {fmt. Printf ("%s Chan finish\n", time. Now ())return} } }}funcMain () {m1 = Make(Map[int]int, max) m2 = Make(Map[int]int, max) ch = Make(ChanOP)GoWait_for_chan (m2) forI: =0; i < Max; i++ {GoUpdate_map_by_chan (i)GoUpdate_map_by_mutex (i)} time. Sleep (time. Second *1)}
Output Result:
2015-11-17 17:08:18.06992 +0800 CST Mutex finish
2015-11-17 17:08:18.0709215 +0800 CST chan finish
Mutex performance is slightly better, but Chan is more go, more recommended.