原因:随机的时间为0
package main
import (
"fmt"
"math/rand"
"sync"
"time"
)
func ReadLock(ch chan struct{}, lock sync.RWMutex) {
fmt.Println("wait Rlock")
lock.RLock()
fmt.Println("start Rlock")
rand.Seed(time.Now().UnixNano())
randNum := rand.Intn(2)
t1 := time.NewTicker(time.Second * time.Duration(randNum))
for {
select {
case <-t1.C:
fmt.Println("读锁")
case <-ch:
fmt.Println("channel close")
return
}
}
lock.RUnlock()
fmt.Println("RUlock...")
}
func WriteLock(ch chan struct{}, lock sync.RWMutex) {
fmt.Println("wait Wlock")
lock.Lock()
fmt.Println("start Wlock")
rand.Seed(time.Now().UnixNano())
randNum := rand.Int63n(2)
t2 := time.NewTimer(time.Second * time.Duration(randNum))
for {
select {
case <-t2.C:
fmt.Println("写锁")
case <-ch:
fmt.Println("channel close write groutine")
return
}
}
lock.Unlock()
fmt.Println("RWUnlock...")
}
func main() {
ch := make(chan struct{})
var lock sync.RWMutex
//加读锁
go ReadLock(ch, lock)
time.Sleep(15 * time.Second)
go WriteLock(ch, lock)
time.Sleep(10 * time.Second)
close(ch)
time.Sleep(5 * time.Second)
}
有疑问加站长微信联系(非本文作者)