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:
parent
91d4985651
commit
8b87cce11c
|
@ -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
|
||||
}
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue