为啥读写锁和互斥锁效率没看出来差别啊,囧

2021-09-27 16:21:08 +08:00
 theknotyouknow
package main`

import (
	"sync"
	"testing"
	"time"
)

const (
	cost = 10 * time.Microsecond
)

type RW interface {
	Write()
	Read()
}

type Lock struct {
	count int
	mu    sync.Mutex
}

func (l *Lock) Read() {
	l.mu.Lock()
	time.Sleep(cost)
	_ = l.count
	l.mu.Unlock()
}

func (l *Lock) Write() {
	l.mu.Lock()
	l.count++
	time.Sleep(cost)
	l.mu.Unlock()
}

type RWLock struct {
	count int
	mu    sync.RWMutex
}

func (r *RWLock) Read() {
	r.mu.Lock()
	time.Sleep(cost)
	_ = r.count
	r.mu.Unlock()
}

func (r *RWLock) Write() {
	r.mu.Lock()
	r.count++
	time.Sleep(cost)
	r.mu.Unlock()
}

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 m := 0; m < write*100; m++ {
			wg.Add(1)
			go func() {
				rw.Write()
				wg.Done()
			}()
		}
		wg.Wait()
	}

}

func BenchmarkReadMore(b *testing.B) {
	benchmark(b, &Lock{}, 9, 1)
}

func BenchmarkReadMoreRW(b *testing.B) {
	benchmark(b, &RWLock{}, 9, 1)
}

func BenchmarkWriteMore(b *testing.B) {
	benchmark(b, &Lock{}, 1, 9)
}

func BenchmarkWriteMoreRW(b *testing.B) {
	benchmark(b, &RWLock{}, 1, 9)
}

func BenchmarkReadEqual(b *testing.B) {
	benchmark(b, &Lock{}, 5, 5)
}

func BenchmarkReadEqualRW(b *testing.B) {
	benchmark(b, &RWLock{}, 5, 5)
}

下面这是我的执行结果:

goarch: amd64
pkg: test
cpu: Intel(R) Core(TM) i5-8257U CPU @ 1.40GHz
|BenchmarkReadMore-8| 62| 18909825| ns/op|
|BenchmarkReadMoreRW-8 | 63| 18825713 |ns/op | |BenchmarkWriteMore-8 | 63 | 18774136| ns/op | |BenchmarkWriteMoreRW-8 | 63 | 20889956 ns/op | PASS
ok test 5.407s

1598 次点击
所在节点    Go 编程语言
3 条回复
lcdtyph
2021-09-27 16:27:11 +08:00
RLock, RUnlock
lcdtyph
2021-09-27 16:30:10 +08:00
你加的全是写锁,没有读锁
theknotyouknow
2021-09-27 16:31:44 +08:00
@lcdtyph 感谢感谢~

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/804647

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX