Last active
November 27, 2019 06:43
-
-
Save alex-leonhardt/cde031809869736cca0b15b5879ed73a to your computer and use it in GitHub Desktop.
concurrently run a command using waitGroups and channels
This file contains hidden or 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 | |
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