一、读写互斥锁
package main
import (
"fmt"
"sync"
"time"
)
//读写互斥锁
var (
x = 0
wg sync.WaitGroup
lock sync.Mutex
rwlock sync.RWMutex
)
func read() {
defer wg.Done()
rwlock.RLock()
fmt.Println(x)
time.Sleep(time.Millisecond)
rwlock.RUnlock()
}
func write() {
defer wg.Done()
rwlock.Lock()
x = x + 1
time.Sleep(time.Millisecond * 5)
rwlock.Unlock()
}
func main() {
start := time.Now()
for i := 0; i < 10; i++ {
go write()
wg.Add(1)
}
time.Sleep(time.Second)
for i := 0; i < 1000; i++ {
go read()
wg.Add(1)
}
wg.Wait()
fmt.Println(time.Now().Sub(start))
}
二、互斥锁
package main
import (
"fmt"
"sync"
"time"
)
//互斥锁
var (
x = 0
wg sync.WaitGroup
lock sync.Mutex
rwlock sync.RWMutex
)
func read() {
defer wg.Done()
lock.Lock()
fmt.Println(x)
time.Sleep(time.Millisecond)
lock.Unlock()
}
func write() {
defer wg.Done()
lock.Lock()
x = x + 1
time.Sleep(time.Millisecond * 5)
lock.Unlock()
}
func main() {
start := time.Now()
for i := 0; i < 10; i++ {
go write()
wg.Add(1)
}
time.Sleep(time.Second)
for i := 0; i < 1000; i++ {
go read()
wg.Add(1)
}
wg.Wait()
fmt.Println(time.Now().Sub(start))
}
三、结论
如上述代码所示,读的操作有1000次,写的操作有10次。当读的操作要远远大于写的操作的时候,读写互斥锁的效率一定是比互斥锁效率要高的。因为这1000次读就不需要别人去等了,当获取读锁的时候其他人还是能读到;只有在获取写入锁的时候,其他人才需要等待。