go官方应该是更推荐使用chan
https://github.com/golang/go/wiki/MutexOrChannel
package main
import (
"fmt"
"sync"
"time"
)
type Op struct {
key int
val int
}
var lock sync.Mutex
var m1 map[int]int
var m2 map[int]int
var max int = 50000
func update_map_by_mutex(i int) {
lock.Lock()
m1[i] = i
if len(m1) == max {
fmt.Printf("%s mutex finish\n",time.Now())
}
lock.Unlock()
}
var ch chan Op
func update_map_by_chan(i int) {
ch <- Op{key: i,val: i}
}
func wait_for_chan(m map[int]int) {
for {
select {
case op := <-ch:
m[op.key] = op.val
if len(m2) == max {
fmt.Printf("%s chan finish\n",time.Now())
return
}
}
}
}
func main() {
m1 = make(map[int]int,max)
m2 = make(map[int]int,max)
ch = make(chan Op)
go wait_for_chan(m2)
for i := 0; i < max; i++ {
go update_map_by_chan(i)
go update_map_by_mutex(i)
}
time.Sleep(time.Second * 1)
}
输出结果:
2015-11-17 17:08:18.06992 +0800 CST mutex finish
2015-11-17 17:08:18.0709215 +0800 CST chan finish
mutex性能略好,但chan更go化,更推荐。