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)
This commit is contained in:
raul 2024-03-07 17:59:18 +01:00
parent 91d4985651
commit 8b87cce11c
2 changed files with 33 additions and 6 deletions

View File

@ -9,12 +9,16 @@ import (
var numsToSum []int var numsToSum []int
var choice2 int var choice2 int
// TODO: Get function done func getAverage(arr []int, c chan int) {
func getAverage() { sum := 0
for i := 0; i < len(arr); i++ {
sum = sum + arr[i]
} }
func addToVec(num int, c chan int) { c <- sum
}
func addToVec(num int) {
numsToSum = append(numsToSum, num) numsToSum = append(numsToSum, num)
} }
@ -39,7 +43,10 @@ func getNumToAdd() (num int) {
} }
func fun2() { func fun2() {
// Create channel made for int values
c := make(chan int) c := make(chan int)
looper: looper:
for { for {
clear() clear()
@ -48,14 +55,31 @@ looper:
getChoice2() getChoice2()
switch choice2 { switch choice2 {
// TODO: Add options to add numbers to array and then to calcluate them later
case 1: case 1:
numToAdd := getNumToAdd() numToAdd := getNumToAdd()
addToVec(numToAdd, c) addToVec(numToAdd)
fmt.Printf("Succesfully added %v to the array\n", numToAdd) fmt.Printf("Succesfully added %v to the array\n", numToAdd)
time.Sleep(time.Second) time.Sleep(time.Second)
case 2: 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: case 3:
break looper break looper
} }

View File

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"os" "os"
"strconv" "strconv"
"time"
) )
var check bool = false var check bool = false
@ -14,6 +15,7 @@ func main() {
var numChoice int var numChoice int
for { for {
clear()
fmt.Printf("[1] Basic concurrency\n") fmt.Printf("[1] Basic concurrency\n")
fmt.Printf("[2] Channels\n") fmt.Printf("[2] Channels\n")
@ -32,6 +34,7 @@ func main() {
os.Exit(0) os.Exit(0)
default: default:
fmt.Printf("Choose an actual function, please\n") fmt.Printf("Choose an actual function, please\n")
time.Sleep(time.Second)
} }
} }