Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
51b9431
commit 705c79b
Showing
2 changed files
with
49 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,5 +3,5 @@ package main | |
import "explore-go/test" | ||
|
||
func main() { | ||
test.BufferedChannel() | ||
test.SelectChannel() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package test | ||
|
||
import ( | ||
"fmt" | ||
"runtime" | ||
) | ||
|
||
func SelectChannel() { | ||
runtime.GOMAXPROCS(2) | ||
|
||
numbers := []int{3, 4, 3, 5, 6, 7, 8, 9, 3, 2} | ||
fmt.Println("numbers :", numbers) | ||
ch1 := make(chan float64) | ||
go getAvarage(numbers, ch1) | ||
|
||
ch2 := make(chan int) | ||
go getMax(numbers, ch2) | ||
|
||
for i := 0; i < 2; i++ { | ||
select { | ||
case avg := <-ch1: | ||
fmt.Printf("Avg \t: %.2f \n", avg) | ||
|
||
case max := <-ch2: | ||
fmt.Printf("Max \t: %d \n", max) | ||
} | ||
} | ||
} | ||
|
||
func getAvarage(numbers []int, ch chan float64) { | ||
sum := 0 | ||
for _, e := range numbers { | ||
sum += e | ||
} | ||
|
||
ch <- float64(sum) / float64(len(numbers)) | ||
} | ||
|
||
func getMax(numbers []int, ch chan int) { | ||
max := numbers[0] | ||
for _, e := range numbers { | ||
if max < e { | ||
max = e | ||
|
||
} | ||
} | ||
ch <- max | ||
} |