54 lines
994 B
Go
54 lines
994 B
Go
package main
|
||
|
||
import (
|
||
"fmt"
|
||
"sync"
|
||
"time"
|
||
)
|
||
|
||
// 读写互斥锁,读的时候远远大于写的场景
|
||
// rwlock
|
||
// 当读的时候加读锁,写的时候加写锁。和互斥锁相比性能差很多
|
||
// 当持有写锁,所有的goroutine都需要等待写锁解锁不能读也不能写,当持有读锁,所有goroutine仍然能够读访问共享资源,但不允许写
|
||
var (
|
||
v = 0
|
||
locker sync.Mutex
|
||
w sync.WaitGroup
|
||
rwlocker sync.RWMutex
|
||
)
|
||
|
||
func read() {
|
||
defer w.Done()
|
||
locker.Lock()
|
||
//rwlocker.RLock()
|
||
fmt.Println(v)
|
||
time.Sleep(time.Millisecond * 1)
|
||
locker.Unlock()
|
||
//rwlocker.RUnlock()
|
||
}
|
||
|
||
func write() {
|
||
defer w.Done()
|
||
locker.Lock()
|
||
//rwlocker.Lock()
|
||
v += 1
|
||
time.Sleep(time.Millisecond * 5)
|
||
locker.Unlock()
|
||
//rwlocker.Unlock()
|
||
}
|
||
|
||
func main() {
|
||
start := time.Now()
|
||
for i := 0; i < 10; i++ {
|
||
w.Add(1)
|
||
go write()
|
||
}
|
||
time.Sleep(time.Second)
|
||
for i := 0; i < 1000; i++ {
|
||
w.Add(1)
|
||
go read()
|
||
}
|
||
w.Wait()
|
||
fmt.Println(time.Now().Sub(start))
|
||
}
|