Advertisement
Guest User

Goroutines synchronising

a guest
Jan 9th, 2024
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Go 1.71 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4.     "fmt"
  5.     "math/rand"
  6.     "sync"
  7.     "time"
  8. )
  9.  
  10. var wg sync.WaitGroup
  11.  
  12. func getSubArraySum(start, end int, arr []int, channel chan<- int) {
  13.     //Gets the sum for the subaray specified by start and end indices
  14.     defer wg.Done()
  15.     total := 0
  16.     for ind := start; ind < end; ind++ {
  17.         total += arr[ind]
  18.     }
  19.     fmt.Println("Start and end indices are: ", start, end)
  20.     fmt.Println("My sum is: ", total)
  21.     //Pass the calculated total into the channel
  22.     channel <- total
  23. }
  24.  
  25. func main() {
  26.     //Find sum of an array using goroutines and channels:
  27.     //Take user input to decide size of array to be summed
  28.     var arraySize int
  29.     fmt.Println("Input size of array:")
  30.     fmt.Scanln(&arraySize)
  31.     //Generate an array of this size filled with random integers
  32.     var newArr []int
  33.     s1 := rand.NewSource(time.Now().UnixNano())
  34.     r1 := rand.New(s1)
  35.     for i := 0; i < arraySize; i++ {
  36.         newArr = append(newArr, r1.Intn(100))
  37.     }
  38.     fmt.Println("The created array is: ")
  39.     for _, value := range newArr {
  40.         fmt.Printf("%d ", value)
  41.     }
  42.     fmt.Println()
  43.     //Create a channel into which the goroutines will pass the calculated total:
  44.     newChan := make(chan int, 2)
  45.     //Create 2 goroutines and calculate sum
  46.     wg.Add(2) //Set waitGroup counter to number of goroutines to be waited for
  47.     go getSubArraySum(0, arraySize/2, newArr, newChan)
  48.     go getSubArraySum(arraySize/2, arraySize, newArr, newChan)
  49.  
  50.     //Use another goroutine to wait for the two other goroutines to finish and close the channel
  51.  
  52.     go func() {
  53.         wg.Wait() //Wait for the two created goroutines to finish
  54.         fmt.Println("The end")
  55.         close(newChan)
  56.     }()
  57.     fmt.Println("Waiting...")
  58.     total := 0
  59.     for val := range newChan {
  60.         total += val
  61.     }
  62.     fmt.Println("Total sum is: ", total)
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement