Performance comparison of Golang read-write lock and mutual exclusion lock

Source: Internet
Author: User

For a long time to think that reading and writing less scenes, read-write lock performance is necessarily better than the mutex, but the opposite is true

No nonsense, first a test code

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
}

Each plus lock 50 million times, the time comparison is as follows:

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

In some scenarios, mutexes are faster than read and write locks!!!



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.