go 协程 读写锁 和互斥锁 使用场景
读多写少 使用读写锁
读少写多 使用互斥锁
读写锁的性能是互斥锁的100倍
package main
import (
"fmt"
"math/rand"
"sync"
"sync/atomic"
"time"
)
func main() {
testMap()
}
var lock sync.Mutex //互斥锁
var rwLock sync.RWMutex //读写锁
func testMap() {
var a map[int]int
a = make(map[int]int, 5)
var count int32
[8] = 10
a[3] = 10
a[2] = 10
a[1] = 10
a[18] = 10
//读写锁 使用场景 读多写小
//互斥锁 写很多 就得用互斥锁
for i := 0; i < 2; i++ {
go func(b map[int]int) {
// lock.Lock() //加互斥锁
rwLock.Lock() //加读写锁
b[8] = rand.Intn(100)
time.Sleep(10 * time.Millisecond)
// lock.Unlock() //解互斥锁
rwLock.Unlock() //解读写锁
}(a)
}
for i := 0; i < 100; i++ {
go func(b map[int]int) {
for {
// lock.Lock()
rwLock.RLock() //加锁 读写锁
// fmt.Println(a)
time.Sleep(time.Millisecond)
// lock.Unlock()
rwLock.RUnlock() //解锁
atomic.AddInt32(&count, 1) //原子操作 加1
}
}(a)
}
time.Sleep(3 * time.Second)
fmt.Println(count)
// lock.Lock() //加锁
// fmt.Println(a)
}