• 微信公众号：美女很有趣。 工作之余，放松一下，关注即送10G+美女照片！

# Golang网课-比较互斥锁与读写互斥锁的耗时

3天前 6次浏览

```package main

import (
"fmt"
"sync"
"time"
)

var (
x     int64
wg    sync.WaitGroup
rwlck sync.RWMutex //读写锁类型变量
)

func write() {
defer wg.Done()
rwlck.Lock() //写锁
x = x + 1
time.Sleep(time.Millisecond * 10) //写操作：10ms
rwlck.Unlock()                    //解写锁
}

defer wg.Done()
rwlck.RLock() //读锁
time.Sleep(time.Millisecond) //读操作：1ms
rwlck.RUnlock()              //解读锁
}

func main() {
start := time.Now()

for i := 0; i < 10; i++ {
go write()
}

for i := 0; i < 100; i++ {
}

end := time.Now()

fmt.Println(end.Sub(start)) //平均耗时约 0.5 ms
}```

```package main

import (
"fmt"
"sync"
"time"
)

var (
x     int64
wg    sync.WaitGroup
lck   sync.Mutex
)

func write() {
defer wg.Done()

lck.Lock() //加互斥锁
x = x + 1
time.Sleep(time.Millisecond * 10) //写操作耗时 10 毫秒
lck.Unlock()                      //解锁
}

defer wg.Done()

lck.Lock()
time.Sleep(time.Millisecond) //读操作耗时 1 毫秒
lck.Unlock()
}

func main() {
start := time.Now()

for i := 0; i < 10; i++ {
go write()
}

for i := 0; i < 100; i++ {
}

wg.Wait()

end := time.Now()

fmt.Println(end.Sub(start))  //平均耗时约 1.75 s
}```