6. 超时控制

此开源图书由ithaiq原创,创作不易转载请注明出处

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())
}

这里要注意一点的是channel如果不是缓冲的,超时后go协程阻塞退不了会造成内存泄漏

最后更新于

这有帮助吗?