Skip to content

Instantly share code, notes, and snippets.

@campoy
Last active Dec 28, 2015
Embed
What would you like to do?
Running concurrently a list of commands
package main
type Command interface {
Run() error
}
func RunAll(cmds []Command) error {
for _, cmd := range cmds {
err := cmd.Run()
if err != nil {
return err
}
}
return nil
}
func RunAllConc(cmds []Command) error {
// We use a buffered channel to avoid goroutine leaking.
errc := make(chan error, len(cmds))
for _, cmd := range cmds {
// We pass the command as a parameter to avoid a data race.
go func(c Command) {
errc <- c.Run()
}(cmd)
}
// We iterate len(cmds) times.
for _ = range cmds {
err := <-errc
if err != nil {
return err
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment