6. 超时控制
func test() error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
ch := make(chan struct{}, 1)
go func() {
time.Sleep(time.Second * 3)
fmt.Printf("执行到这里:%p\n", ch)
ch <- struct{}{}
}()
select {
case <-ctx.Done():
println("超时")
return errors.New("超时")
case <-ch:
return nil
}
}
func main() {
for i := 0; i < 50; i++ {
go test()
}
time.Sleep(time.Second * 5)
fmt.Println(runtime.NumGoroutine())
}最后更新于