patterngoMinor
Return results from goroutines
Viewed 0 times
returnresultsfromgoroutines
Problem
I have two goroutines that each need to return their results to the main function. These results are of different types.
I have implemented a solution that uses a structure that holds these results. The structure is passed to the routines and each routine knows which field in the structure to use to save the results.
I am new to Golang and I am not sure if this is an elegant solution. Maybe channels are more suitable?
https://play.golang.org/p/XW1LccJvAn
I have implemented a solution that uses a structure that holds these results. The structure is passed to the routines and each routine knows which field in the structure to use to save the results.
I am new to Golang and I am not sure if this is an elegant solution. Maybe channels are more suitable?
package main
import (
"fmt"
"sync"
)
type Results struct {
x float64
y int
}
func main() {
var r Results
var wg sync.WaitGroup
wg.Add(2)
go func(r *Results, wg *sync.WaitGroup) {
defer wg.Done()
r.x = 1.2
}(&r, &wg)
go func(r *Results, wg *sync.WaitGroup) {
defer wg.Done()
r.y = 34
}(&r, &wg)
wg.Wait()
fmt.Println(r)
}https://play.golang.org/p/XW1LccJvAn
Solution
Using a structure and waitgroups is silly for something this simple.
Just make two channels and fire off two goroutines. You don't care which one finishes first just read from both channels in whatever order is convenient (or even do something like
E.g.:
https://play.golang.org/p/Qoh5IvFROo
Just make two channels and fire off two goroutines. You don't care which one finishes first just read from both channels in whatever order is convenient (or even do something like
someOtherFunction(<-c1, <-c2)).E.g.:
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
c1 := make(chan float64, 1)
c2 := make(chan int, 1)
go func() {
// simulate spending time to do work to get answer
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
c1 <- 1.2
}()
go func() {
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
c2 <- 34
}()
x := <-c1
y := <-c2
fmt.Println(x, y)
}https://play.golang.org/p/Qoh5IvFROo
Code Snippets
package main
import (
"fmt"
"math/rand"
"time"
)
func main() {
c1 := make(chan float64, 1)
c2 := make(chan int, 1)
go func() {
// simulate spending time to do work to get answer
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
c1 <- 1.2
}()
go func() {
time.Sleep(time.Duration(rand.Intn(2000)) * time.Millisecond)
c2 <- 34
}()
x := <-c1
y := <-c2
fmt.Println(x, y)
}Context
StackExchange Code Review Q#77106, answer score: 4
Revisions (0)
No revisions yet.