github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgTime/timeout.go (about) 1 package kmgTime 2 3 import ( 4 "errors" 5 "time" 6 ) 7 8 var ErrTimeOut = errors.New("time out") 9 10 func Timeout(f func(), dur time.Duration) (hasTimeout bool) { 11 finishChan := make(chan struct{}) 12 go func() { 13 f() 14 finishChan <- struct{}{} 15 }() 16 select { 17 case <-finishChan: 18 return false 19 case <-time.After(dur): 20 return true 21 } 22 } 23 24 func MustNotTimeout(f func(), dur time.Duration) { 25 finishChan := make(chan struct{}) 26 go func() { 27 select { 28 case <-finishChan: 29 return 30 case <-time.After(dur): 31 panic(ErrTimeOut) 32 } 33 }() 34 f() 35 finishChan <- struct{}{} 36 return 37 }