fox/safeChan/safeChan_test.go

73 lines
1.1 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package safeChan
import (
"github.com/fox/fox/ksync"
"github.com/fox/fox/log"
"testing"
"time"
)
func initLog() {
log.Open("test.log", log.DebugL)
}
func OriginChanPanic(t *testing.T) {
och := make(chan string, 10)
go func() {
och <- "hello"
t.Log("write hello")
close(och)
//close(och) // 多次关闭也会panic
}()
time.Sleep(time.Millisecond)
t.Log("origin chan was closed")
ksync.GoSafe(func() {
och <- "world"
}, nil)
}
func SafeChanNoPanic(t *testing.T) {
ch := NewSafeChan[string](12)
go func() {
_ = ch.Write("hello")
t.Log("write hello. 剩余数量:", ch.Size())
}()
ch.Close()
if err := ch.Write("zzz"); err != nil {
t.Log("write zzz err.", err)
}
breakNum := 0
for {
select {
case v, ok := <-ch.Reader():
if ok {
t.Log("read", v, " 剩余数量:", ch.Size())
} else {
t.Log("break")
breakNum++
}
default:
t.Log("panic")
breakNum++
}
if breakNum > 10 {
break
}
}
}
func TestSafeChan(t *testing.T) {
initLog()
OriginChanPanic(t)
time.Sleep(time.Second * 1)
SafeChanNoPanic(t)
// 防止主协程过早退出导致go协程里无法打印
time.Sleep(time.Second * 1)
}