Skip to content

Instantly share code, notes, and snippets.

@alex-leonhardt
Last active November 27, 2019 06:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alex-leonhardt/cde031809869736cca0b15b5879ed73a to your computer and use it in GitHub Desktop.
Save alex-leonhardt/cde031809869736cca0b15b5879ed73a to your computer and use it in GitHub Desktop.
concurrently run a command using waitGroups and channels
package main
import (
"fmt"
"math/rand"
"os/exec"
"sync"
"time"
)
func doLS(path string) ([]byte, error) {
cmd := exec.Command("ls", "-l", path)
return cmd.CombinedOutput()
}
func main() {
outputs := make(chan string)
var wg sync.WaitGroup
wg.Add(1)
go func() {
out, _ := doLS("/usr")
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
outputs <- string(out)
wg.Done()
}()
wg.Add(1)
go func() {
out, _ := doLS("/")
time.Sleep(time.Duration(rand.Intn(5000)) * time.Millisecond)
outputs <- string(out)
wg.Done()
}()
done := make(chan bool)
go func() {
for m := range outputs {
fmt.Println(m)
}
done <- true
}()
wg.Wait()
close(outputs)
<-done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment