mirror of
https://github.com/CPunch/gopenfusion.git
synced 2024-11-14 03:50:05 +00:00
SelectWithTimeout && WaitWithTImeout now use time.Duration
This commit is contained in:
parent
e33b7c0556
commit
899b95b4e6
@ -8,6 +8,7 @@ import (
|
||||
"os"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/CPunch/gopenfusion/cnet"
|
||||
"github.com/CPunch/gopenfusion/cnet/protocol"
|
||||
@ -20,7 +21,7 @@ var (
|
||||
)
|
||||
|
||||
const (
|
||||
timeout = 2
|
||||
timeout = 2 * time.Second
|
||||
maxDummyPeers = 5
|
||||
)
|
||||
|
||||
|
@ -9,21 +9,21 @@ func GetTime() uint64 {
|
||||
return uint64(time.Now().UnixMilli())
|
||||
}
|
||||
|
||||
func SelectWithTimeout(ch <-chan struct{}, seconds int) bool {
|
||||
func SelectWithTimeout(ch <-chan struct{}, timeout time.Duration) bool {
|
||||
select {
|
||||
case <-ch:
|
||||
return true
|
||||
case <-time.After(time.Duration(seconds) * time.Second):
|
||||
case <-time.After(timeout):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func WaitWithTimeout(wg *sync.WaitGroup, seconds int) bool {
|
||||
func WaitWithTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
wg.Wait()
|
||||
}()
|
||||
|
||||
return SelectWithTimeout(done, seconds)
|
||||
return SelectWithTimeout(done, timeout)
|
||||
}
|
||||
|
@ -13,23 +13,23 @@ func TestWaitWithTimeout(t *testing.T) {
|
||||
is := is.New(t)
|
||||
wg := &sync.WaitGroup{}
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second)
|
||||
time.Sleep(1 * time.Second)
|
||||
wg.Done()
|
||||
}()
|
||||
|
||||
wg.Add(1)
|
||||
is.True(!util.WaitWithTimeout(wg, 1)) // timeout should occur
|
||||
is.True(util.WaitWithTimeout(wg, 2)) // timeout shouldn't occur
|
||||
is.True(!util.WaitWithTimeout(wg, 500*time.Millisecond)) // timeout should occur
|
||||
is.True(util.WaitWithTimeout(wg, 750*time.Millisecond)) // timeout shouldn't occur
|
||||
}
|
||||
|
||||
func TestSelectWithTimeout(t *testing.T) {
|
||||
is := is.New(t)
|
||||
ch := make(chan struct{})
|
||||
go func() {
|
||||
time.Sleep(2 * time.Second)
|
||||
time.Sleep(1 * time.Second)
|
||||
close(ch)
|
||||
}()
|
||||
|
||||
is.True(!util.SelectWithTimeout(ch, 1)) // timeout should occur
|
||||
is.True(util.SelectWithTimeout(ch, 2)) // timeout shouldn't occur
|
||||
is.True(!util.SelectWithTimeout(ch, 500*time.Millisecond)) // timeout should occur
|
||||
is.True(util.SelectWithTimeout(ch, 750*time.Millisecond)) // timeout shouldn't occur
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user