From 8b87cce11cf19e03a8b3ef089fbc63d54852c5b8 Mon Sep 17 00:00:00 2001 From: raul Date: Thu, 7 Mar 2024 17:59:18 +0100 Subject: [PATCH] Completed goroutine channels exercise Finally starting to get the hang of how channels in goroutines work, just pass the values around using arrows after creating the channel using c := make(chan $TYPE) --- golangr/goroutines/2.go | 36 ++++++++++++++++++++++++++++++------ golangr/goroutines/main.go | 3 +++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/golangr/goroutines/2.go b/golangr/goroutines/2.go index 6e541b0..212bb5a 100644 --- a/golangr/goroutines/2.go +++ b/golangr/goroutines/2.go @@ -9,12 +9,16 @@ import ( var numsToSum []int var choice2 int -// TODO: Get function done -func getAverage() { +func getAverage(arr []int, c chan int) { + sum := 0 + for i := 0; i < len(arr); i++ { + sum = sum + arr[i] + } + c <- sum } -func addToVec(num int, c chan int) { +func addToVec(num int) { numsToSum = append(numsToSum, num) } @@ -39,7 +43,10 @@ func getNumToAdd() (num int) { } func fun2() { + + // Create channel made for int values c := make(chan int) + looper: for { clear() @@ -48,14 +55,31 @@ looper: getChoice2() switch choice2 { - // TODO: Add options to add numbers to array and then to calcluate them later + case 1: numToAdd := getNumToAdd() - addToVec(numToAdd, c) + addToVec(numToAdd) fmt.Printf("Succesfully added %v to the array\n", numToAdd) time.Sleep(time.Second) case 2: - getAverage() + // Send function call to goroutine while providing the channel for communication + go getAverage(numsToSum, c) + + fmt.Printf("\rThinking.") + time.Sleep(time.Second) + fmt.Printf("\rThinking..") + time.Sleep(time.Second) + fmt.Printf("\rThinking...") + time.Sleep(time.Second) + fmt.Printf("\r\n") + + // Get the result returned by the goroutine + total := <-c + average := total / len(numsToSum) + + fmt.Printf("The grand total is %v\n", total) + fmt.Printf("The average value is %v\n", average) + time.Sleep(time.Second * 3) case 3: break looper } diff --git a/golangr/goroutines/main.go b/golangr/goroutines/main.go index 093b51d..26c1faa 100644 --- a/golangr/goroutines/main.go +++ b/golangr/goroutines/main.go @@ -4,6 +4,7 @@ import ( "fmt" "os" "strconv" + "time" ) var check bool = false @@ -14,6 +15,7 @@ func main() { var numChoice int for { + clear() fmt.Printf("[1] Basic concurrency\n") fmt.Printf("[2] Channels\n") @@ -32,6 +34,7 @@ func main() { os.Exit(0) default: fmt.Printf("Choose an actual function, please\n") + time.Sleep(time.Second) } }