func BenchmarkMutex(b *testing.B)  {
    var number int
    lock := sync.Mutex{}
    for i:=0; i< b.N;i++{
        go func() {
            defer lock.Unlock()
            lock.Lock()
            number++
        }()
    }
}

func BenchmarkAtomic(b *testing.B)  {
    var number int32
    for i:=0; i< b.N;i++{
        go func() {
            atomic.AddInt32(&number, 1)
        }()
    }
}

用两个函数做性能测试 benchmarkMutex与benchmarkAtomic 来比较互斥锁的差异

$ go test -v -cpu 1,2,4 -benchmem   -bench=.
goos: darwin
goarch: amd64
pkg: puzzlers/article21/q3
BenchmarkMutex           1000000              2949 ns/op             424 B/op          0 allocs/op
BenchmarkMutex-2         5000000               336 ns/op              22 B/op          0 allocs/op
BenchmarkMutex-4        10000000               205 ns/op               0 B/op          0 allocs/op
BenchmarkAtomic          2000000              1745 ns/op             156 B/op          0 allocs/op
BenchmarkAtomic-2       10000000               176 ns/op               0 B/op          0 allocs/op
BenchmarkAtomic-4       10000000               225 ns/op               0 B/op          0 allocs/op
PASS
ok      puzzlers/article21/q3   26.179s

我们发现原子锁的性能高于互斥锁 不管从内存消耗与CPU运行 都比互斥锁要好

01-07 20:41