下面这个代码发现一个问题,当打印超时后,'fmt.Println("haha")' 还是会出错,如何才能做到超时时结束GO 不在输出HAHA
func handleSendaa(){
//生成数据包
chErr:=make(chan error)
ticks:=time.Tick(time.Second*1)
go func(){
<-ticks
fmt.Println("haha")
chErr <- nil
close(chErr)
}()
select {
case <-chErr:
fmt.Println("end")
case <-time.After(time.Millisecond*500):
fmt.Println("TimeOut")
}
}
```
package main
import (
"context"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), 2000*time.Millisecond)
go func(ctx context.Context, cancel context.CancelFunc) {
for {
select {
case _, ok := <-ctx.Done():
if ok {
fmt.Println("return")
cancel()
} else {
fmt.Println("time over")
}
return
}
}
}(ctx, cancel)
select {
case <-time.After(1 * time.Second):
fmt.Println("overslept")
cancel()
}
time.Sleep(10000 * time.Millisecond)
}
```
#5
更多评论