package main
import (
"fmt"
"math/rand"
"sync/atomic"
"time"
)
// 读写
type readOp struct {
key int
resp chan int
}
type writeOp struct {
key int
val int
resp chan bool
}
func main() {
var readOps uint64
var writeOps uint64
reads := make(chan readOp)
writes := make(chan writeOp)
go func() {
var start = make(map[int]int) // 状态存储对象
for {
select {
case read := <-reads:
read.resp <- start[read.key]
case write := <-writes:
start[write.key] = write.val
write.resp <- true
}
}
}()
for r := 0; r < 100; r++ {
go func() {
for {
read := readOp{
key: rand.Intn(5),
resp: make(chan int),
}
reads <- read
<-read.resp
atomic.AddUint64(&readOps, 1)
time.Sleep(time.Microsecond)
}
}()
}
for w := 0; w < 10; w++ {
go func() {
for {
write := writeOp{
key: rand.Intn(5),
val: rand.Intn(100),
resp: make(chan bool),
}
writes <- write
<-write.resp
atomic.AddUint64(&writeOps, 1)
time.Sleep(time.Microsecond)
}
}()
}
time.Sleep(time.Second)
readOpsFinal := atomic.LoadUint64(&readOps)
fmt.Println(readOpsFinal)
writeOpsFinal := atomic.LoadUint64(&writeOps)
fmt.Println(writeOpsFinal)
}
go-基础-读写锁
最新推荐文章于 2024-05-11 07:02:31 发布