Skip to content

Instantly share code, notes, and snippets.

@campoy
Last active December 28, 2015 05:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save campoy/7453248 to your computer and use it in GitHub Desktop.
Save campoy/7453248 to your computer and use it in GitHub Desktop.
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