Last active
December 28, 2015 05:59
-
-
Save campoy/7453248 to your computer and use it in GitHub Desktop.
Running concurrently a list of commands
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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