Question
The following program demonstrates a parallel loop in Go / Golang. However, this program should wait for the go routines to terminate before ending. Remove
The following program demonstrates a parallel loop in Go / Golang. However, this program should wait for the go routines to terminate before ending. Remove the Sleep statement and replace it by a proper goroutine synchronization. Here is the code:
package main
import "fmt"
import "time"
func main() {
x := []int{3, 1, 4, 1, 5, 9, 2, 6}
var y [8]int
// loop parallel
for i, v := range x {
go func (i int, v int) {
y[i]= calcul(v)
}(i,v) // call for the goroutine
}
// add synchronisation
time.Sleep(1*time.Second)
fmt.Println(y)
}
func calcul(v int) (int) {
return 2*v*v*v+v*v
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started