Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

The following program calculates the sum of the square roots of numbers. Each routine runs in its own go routines and sends the message on

The following program calculates the sum of the square roots of numbers. Each routine runs in its own go routines and sends the message on a dedicated channel back to the main program. The program exits to early. Fix the main routine (and only the main routine) to ensure that it finishes with the last received result (not earlier or later). Also make sure that you receive the results in the order they are calculated and not simply sequential in the order the routines are called. (NOTE THIS IS PROGRAMMED IN GO)

package main import ( "fmt" "math" "math/rand" "time" ) func numbers(sz int) (res chan float64) { res = make(chan float64) go func() { defer close(res) num := 0.0 time.Sleep(time.Duration(rand.Intn(1000)) * time.Microsecond) for i := 0; i < sz; i++ { num += math.Sqrt(math.Abs(rand.Float64())) } num /= float64(sz) res <- num return }() return } func main() { var nGo int rand.Seed(42) fmt.Print("Number of Go routines: ") fmt.Scanf("%d ", &nGo) res := make([]chan float64, nGo) for i := 0; i < nGo; i++ { res[i] = numbers(1000) } }

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access with AI-Powered Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Students also viewed these Databases questions