EZVIK
2022-05-18 14:15:39 +08:00
用装饰器模式包装函数
```go
type RunTask func(int) float64
func RunTaskTimeout(fun RunTask, timeout time.Duration) RunTask {
return func(i int) float64 {
ch := make(chan float64)
go func() {
ch <- func(i int) float64 {
return func(i int) float64 {
return fun(i)
}(i)
}(i)
}()
select {
case f := <-ch:
return f
case <-time.After(timeout):
return -1
}
}
}
func main() {
runTask := RunTaskTimeout(Pi, time.Second)
data := []int{500, 5000, 50000, 500000, 5000000}
for i := 0; i < 10; i++ {
if res := runTask(data[i]); res < 0 {
break
} else {
fmt.Println(res)
}
}
fmt.Println("DONE.")
}
```