Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package main
- import (
- "fmt"
- "math/rand"
- "sync"
- "time"
- )
- var wg sync.WaitGroup
- func getSubArraySum(start, end int, arr []int, channel chan<- int) {
- //Gets the sum for the subaray specified by start and end indices
- defer wg.Done()
- total := 0
- for ind := start; ind < end; ind++ {
- total += arr[ind]
- }
- fmt.Println("Start and end indices are: ", start, end)
- fmt.Println("My sum is: ", total)
- //Pass the calculated total into the channel
- channel <- total
- }
- func main() {
- //Find sum of an array using goroutines and channels:
- //Take user input to decide size of array to be summed
- var arraySize int
- fmt.Println("Input size of array:")
- fmt.Scanln(&arraySize)
- //Generate an array of this size filled with random integers
- var newArr []int
- s1 := rand.NewSource(time.Now().UnixNano())
- r1 := rand.New(s1)
- for i := 0; i < arraySize; i++ {
- newArr = append(newArr, r1.Intn(100))
- }
- fmt.Println("The created array is: ")
- for _, value := range newArr {
- fmt.Printf("%d ", value)
- }
- fmt.Println()
- //Create a channel into which the goroutines will pass the calculated total:
- newChan := make(chan int, 2)
- //Create 2 goroutines and calculate sum
- wg.Add(2) //Set waitGroup counter to number of goroutines to be waited for
- go getSubArraySum(0, arraySize/2, newArr, newChan)
- go getSubArraySum(arraySize/2, arraySize, newArr, newChan)
- //Use another goroutine to wait for the two other goroutines to finish and close the channel
- go func() {
- wg.Wait() //Wait for the two created goroutines to finish
- fmt.Println("The end")
- close(newChan)
- }()
- fmt.Println("Waiting...")
- total := 0
- for val := range newChan {
- total += val
- }
- fmt.Println("Total sum is: ", total)
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement