美文网首页
golang panic: non-positive inter

golang panic: non-positive inter

作者: anthonydan | 来源:发表于2020-04-05 17:51 被阅读0次
image.png

原因:随机的时间为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)

}

相关文章

网友评论

      本文标题:golang panic: non-positive inter

      本文链接:https://www.haomeiwen.com/subject/ltfpphtx.html