Search code examples
gotimeout

How to implement a timeout when using sync.WaitGroup.wait?


I have come across a situation that i want to trace some goroutine to sync on a specific point, for example when all the urls are fetched. Then, we can put them all and show them in specific order.

I think this is the barrier comes in. It is in go with sync.WaitGroup. However, in real situation that we can not make sure that all the fetch operation will succeed in a short time. So, i want to introduce a timeout when wait for the fetch operations.

I am a newbie to Golang, so can someone give me some advice?


What i am looking for is like this:

   wg := &sync.WaigGroup{}
   select {
   case <-wg.Wait():
   // All done!
   case <-time.After(500 * time.Millisecond):
   // Hit timeout.
   }

I know Wait do not support Channel.


Solution

  • If all you want is your neat select, you can easily convert blocking function to a channel by spawning a routine which calls a method and closes/sends on channel once done.

    done := make(chan struct{})
    go func() {
       wg.Wait()
       close(done)
    }()
    
    select {
    case <-done:
    // All done!
    case <-time.After(500 * time.Millisecond):
    // Hit timeout.
    }