Tired of Waiting Forever? Adding a Timeout to WaitGroup.Wait()
When you employ WaitGroup.Wait() to synchronize goroutines and ensure they finish executing, you may occasionally desire the ability to terminate waiting after a specific duration. This prevents your system from endlessly relying on errant workers that may never complete their tasks.
A Pragmatic Solution for Timed WaitGroups
One approach to implementing a timeout involves utilizing a combination of goroutines, channels, and the time package. The idea is to create a channel that receives a signal upon the completion of all goroutines. Simultaneously, a timer is initialized with the desired timeout duration. A select statement is used to monitor both the channel and the timer:
import ( "sync" "time" ) func task(wg *sync.WaitGroup) { // Perform some task... time.Sleep(time.Second * 2) wg.Done() } func main() { var wg sync.WaitGroup wg.Add(2) go task(&wg) go task(&wg) ch := make(chan struct{}) defer close(ch) go func() { defer wg.Done() wg.Wait() close(ch) }() timeout := 5*time.Second select { case <-ch: fmt.Println("All jobs completed within timeout.") case <-time.After(timeout): fmt.Println("Timeout reached, not all jobs completed.") } }
Simplifying the Timeout with Helper Functions
To offer a more convenient and reusable approach, consider creating a helper function that encapsulates this functionality:
func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool { c := make(chan struct{}) go func() { defer close(c) wg.Wait() }() select { case <-c: return false case <-time.After(timeout): return true } }
This helper function accepts a WaitGroup and a desired timeout duration and returns whether or not the wait exceeded the specified limit.
Usage of the Helper Function
Utilizing the helper function is straightforward:
if waitTimeout(&wg, 5*time.Second) { fmt.Println("Timeout reached waiting for wait group.") }
In this example, the waitTimeout function returns true if the wait group takes longer than 5 seconds to complete, indicating that a timeout has occurred.
The above is the detailed content of How to Add a Timeout to WaitGroup.Wait() in Go?. For more information, please follow other related articles on the PHP Chinese website!