我希望为一个名为foo
的函数设置超时.请考虑以下几点
func fooWithTimeout(d time.Duration) error {
ch := make(chan error, 1)
go func() {
ch <- foo()
}()
select {
case err := <-ch:
return err
case <-time.After(d):
return errors.New("foo has timed out")
}
}
- 如果
foo
已经超时,那么foo
是否能够写入通道ch
,或者是否存在Goroutine阻塞或死机的风险? - 一旦
fooWithTimeout
退出,通道ch
会发生什么情况? - 此代码是否存在潜在问题?
- 在拨打
foo
之前,我应该在go func(){...}()
内加defer close(ch)
吗? - 在本例中,我使用缓冲通道(大小为1)还是非缓冲通道有关系吗?