Skip to content

Instantly share code, notes, and snippets.

@marshyon
Created January 24, 2023 21:14
Show Gist options
  • Save marshyon/c10461e0e51a2a355cb06dd62f9b6f8a to your computer and use it in GitHub Desktop.
Save marshyon/c10461e0e51a2a355cb06dd62f9b6f8a to your computer and use it in GitHub Desktop.
Golang run and wait for many go routines using channels and returning a struct of result data for each process
package main
import (
"fmt"
"log"
"math/rand"
"time"
)
type SystemCommandResult struct {
ExitCode int
OutputString string
RunTime string
}
const numberOfJobs = 50
func longTimeRequest() <-chan SystemCommandResult {
r := make(chan SystemCommandResult)
go func() {
// Simulate a workload with random duration
waitTime := rand.Int31n(5)
time.Sleep(time.Second * time.Duration(waitTime))
randomNumber := rand.Int31n(100)
result := SystemCommandResult{
ExitCode: 0,
OutputString: fmt.Sprintf("workload completed [%d]", randomNumber),
RunTime: fmt.Sprintf("%d seconds", waitTime),
}
r <- result
}()
return r
}
func waitForChannel(r SystemCommandResult) SystemCommandResult {
return SystemCommandResult{
ExitCode: r.ExitCode,
OutputString: r.OutputString,
RunTime: r.RunTime,
}
}
func main() {
rand.Seed(time.Now().UnixNano()) // before Go 1.20
// list of channels
var resultChannels []<-chan SystemCommandResult
// create channels
for i := 0; i < numberOfJobs; i++ {
resultChannels = append(resultChannels, longTimeRequest())
}
// iterate over channels
for id, resultChannel := range resultChannels {
currentResult := waitForChannel(<-resultChannel)
log.Printf("[%d] exit : %d, output : %s, time : %s\n", id, currentResult.ExitCode, currentResult.OutputString, currentResult.RunTime)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment