Hi, abandon
← 文章列表

给 Go 函数调用加上超时和默认返回值

2023年9月30日 · other / blog


func callFunctionWithTimeout[R any, T func() R](f T, timeout time.Duration, defaultValue R) R {
	var result R
	var mu sync.Mutex
	done := make(chan bool, 1)

	go func() {
		result = f()
		mu.Lock()
		defer mu.Unlock()
		done <- true
	}()

	select {
	case <-done:
		return result
	case <-time.After(timeout):
		mu.Lock()
		defer mu.Unlock()
		return defaultValue
	}
}
想聊聊这篇文章?去 GooseForum 讨论 ← 返回文章列表