golang讀寫鎖與互斥鎖的效能比較

來源:互聯網
上載者:User

長時間來一直以為在讀多寫少的情境下,讀寫鎖效能必然優於互斥鎖,然而情況恰恰相反

不廢話了,先上一段測試代碼

func main() {
var w = &sync.WaitGroup{}
var num = 50000000
var c = make(chan int, 3000)

var rwmutexTmp = newRwmutex()
w.Add(num)
t1 := time.Now()
for i := 0; i < num; i++ {
c <- 0
go func(index int) {
defer w.Done()
_ = rwmutexTmp.get(index)
//fmt.Println(value)
<-c
}(i)
}
w.Wait()
t2 := time.Now()

var mutexTmp = newMutex()
w.Add(num)
t3 := time.Now()
for i := 0; i < num; i++ {
c <- 0
go func(index int) {
defer w.Done()
t := mutexTmp.get()
_, _ = t[index]
//fmt.Println(ok)
<-c
}(i)
}
w.Wait()
t4 := time.Now()
fmt.Println("rwmutex cost:", t2.Sub(t1).String())
fmt.Println("mutex cost:", t4.Sub(t3).String())
}

type rwmutex struct {
mu *sync.RWMutex
ipmap map[int]int
}

type mutex struct {
mu *sync.Mutex
ipmap map[int]int
}

func (t *rwmutex) get(i int) int {
t.mu.RLock()
defer t.mu.RUnlock()

return t.ipmap[i]
}


func (t *mutex) get() map[int]int {
t.mu.Lock()
defer t.mu.Unlock()

return t.ipmap
}

func newRwmutex() *rwmutex {
var t = &rwmutex{}
t.mu = &sync.RWMutex{}
t.ipmap = make(map[int]int, 100)

for i := 0; i < 100; i++ {
t.ipmap[i] = 0
}
return t
}

func newMutex() *mutex {
var t = &mutex{}
t.mu = &sync.Mutex{}
t.ipmap = make(map[int]int, 100)

for i := 0; i < 100; i++ {
t.ipmap[i] = 0
}
return t
}

各加鎖5000萬次,時間比較如下:

go run test_rwmutex_mutex.go 

  rwmutex cost: 22.403487195s

  mutex cost: 21.636404963s

go run test_rwmutex_mutex.go 

  rwmutex cost: 22.3359224s

  mutex cost: 21.931208658s

 

在某些情境下,互斥鎖要比讀寫鎖更快!!!



相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.