1

My scenario is I want to fire multiple go routines that listens to network traffic, if there is an error in one of the go routine function, function will execute wg.done() and this for loop should wait for other go routines to execute wg.done() and after some time, like ten minutes of sleep this for loop should run again. This is something like a retry logic. Can someone help with this. Thanks. Below is the code I came up with so far.

package main

import (
    "errors"
    "fmt"
    "sync"
)

func main() {

    var wg sync.WaitGroup
    for {
        wg.Add(1)
        go A(&wg)
        wg.Add(1)
        go B(&wg)

    }
    wg.Wait()

}

func A(wg *sync.WaitGroup) {

    fmt.Println("inside function A")

    err := errors.New("There is an error")
    if err != nil {
        wg.Done()
    }

}

func B(wg *sync.WaitGroup) {

    fmt.Println("Inside function B")

    err := errors.New("There is an error")
    if err != nil {
        wg.Done()
    }

}

1 Answer 1

2

Your wg.Wait() never runs as it's outside the infinite-loop.

I'm guessing you're looking for something like this?

for {
    tC := time.After(10 * time.Minute) // start timer before workers
    
    wg.Add(1)
    go A(&wg)

    wg.Add(1)
    go B(&wg)

    wg.Wait() // waits for both A & B to complete - whether they succeed or not

    <-tC // wait for remainder of 10 minutes before retrying
}

Playground Example

One caveat with the above: if A & B take longer than 10 minutes to complete, then the timer fires and <-tC will not wait - causing the loop to restart immediately.


Finally, if you want to ensure A or B do not take longer than 10 minutes to run, then your worker goroutines should look into leveraging the context package. Passing in a context via, say context.WithTimeout(...), you can ensure the worker will exit, once the context cancels (i.e. times out).

Sign up to request clarification or add additional context in comments.

2 Comments

This is helpful. Thank you.
@SaiBagam please accept the answer if it met your needs and to close out the question. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.