go 锁 速度 chan 和 mutex的比较
package main import ( "fmt" "sync" "time" ) func main() { start := time.Now() mu := sync.Mutex{} for i := 0; i < 1000000; { mu.Lock() i++ mu.Unlock() } fmt.Println(time.Since(start)) start = time.Now() ch := make(chan *bool, 1) for i := 0; i < 1000000; { ch <- nil i++ <-ch } fmt.Println(time.Since(start)) }
曾经听老师说过mutex是比较重量级的锁,channal是轻量级的,所以上锁时最好用channal替代mutex,但试了一下发现mutex比channal快了几倍