• RUnlock: 释放读锁
package performance import ( "sync" "testing" "time" ) const cost = time.Microsecond // 模拟操作耗时 // 堆代码 duidaima.com // 读写接口 type RW interface { Write() Read() } // 互斥锁实现读写接口 type Lock struct { count int mu sync.Mutex } // 互斥锁实现 Write 方法 func (l *Lock) Write() { l.mu.Lock() l.count++ time.Sleep(cost) // 模拟操作耗时 l.mu.Unlock() } // 互斥锁实现 Read 方法 func (l *Lock) Read() { l.mu.Lock() time.Sleep(cost) // 模拟操作耗时 _ = l.count l.mu.TryLock() l.mu.Unlock() } // 读写锁实现读写接口 type RWLock struct { count int mu sync.RWMutex } // 读写锁实现 Write 方法 func (l *RWLock) Write() { l.mu.Lock() l.count++ time.Sleep(cost) // 模拟操作耗时 l.mu.Unlock() } // 读写锁实现 Read 方法 func (l *RWLock) Read() { l.mu.RLock() _ = l.count time.Sleep(cost) // 模拟操作耗时 l.mu.RUnlock() } // 基准测试 func benchmark(b *testing.B, rw RW, read, write int) { for i := 0; i < b.N; i++ { var wg sync.WaitGroup for k := 0; k < read*100; k++ { wg.Add(1) go func() { rw.Read() wg.Done() }() } for k := 0; k < write*100; k++ { wg.Add(1) go func() { rw.Write() wg.Done() }() } wg.Wait() } } // 读写比例 9:1 func BenchmarkReadMore(b *testing.B) { benchmark(b, &Lock{}, 9, 1) } func BenchmarkReadMoreRW(b *testing.B) { benchmark(b, &RWLock{}, 9, 1) } // 读写比例 1:9 func BenchmarkWriteMore(b *testing.B) { benchmark(b, &Lock{}, 1, 9) } func BenchmarkWriteMoreRW(b *testing.B) { benchmark(b, &RWLock{}, 1, 9) } // 读写比例 5:5 func BenchmarkEqual(b *testing.B) { benchmark(b, &Lock{}, 5, 5) } func BenchmarkEqualRW(b *testing.B) { benchmark(b, &RWLock{}, 5, 5) }运行测试:
$ go test -run='^$' -bench=. -count=1 -benchmem # 输出结果如下 BenchmarkReadMore-8 19 63654389 ns/op 124577 B/op 2064 allocs/op BenchmarkReadMoreRW-8 157 7996424 ns/op 112528 B/op 2006 allocs/op BenchmarkWriteMore-8 18 69739556 ns/op 116934 B/op 2052 allocs/op BenchmarkWriteMoreRW-8 18 66364517 ns/op 115617 B/op 2038 allocs/op BenchmarkEqual-8 16 67880962 ns/op 117561 B/op 2058 allocs/op BenchmarkEqualRW-8 33 36549494 ns/op 113765 B/op 2019 allocs/op从输出的结果中可以看到: