Search code examples
gowait

Concurrency Design in golang - wait for a certain number of goroutines


I have a list of 10 servers, out of which one of those servers is a primary. It has the responsibility of sending a request to remaining 9 servers and has to wait for a reply for at least 5 of them. I can send these requests asynchronously using goroutines, and once I have received the reply from at least 5 of them, I can proceed with my execution. How do I design this using go, in general? Feel free to use any tools you like. You can assume these 10 servers are isolated, and have nothing shared between them.


Solution

  • Since you are communicating with remote servers, it probably makes sense to have a context.Context that gets canceled once 5 of your 10 requests complete. You would pass that context to whatever network function you are using.

    For example:

    ctx, cancel := context.WithCancel(context.Background())
    n := int32(10)
    // Inside the goroutine
    if atomic.AddInt32(&n, -1) == 5 {
        cancel()
    }
    <-ctx.Done() // returns once the context is canceled