1, create new project "test11_channel"
$ cd ~/project
$ mkdir test11_channel
$ cd test11_channel
$ touch channel.go
2,add following lines in “channel.go”
package main
import (
"fmt"
"time"
)
func main() {
// TEST 1, goroutine
var n1, n2 string = "pang pamg", "nao nao"
go greet(n1)
greet(n2)
// TEST 2, channel
var chn = make(chan(int), 1)
var num1 = []int{1, 2, 3, 4, 5}
var num2 = []int{6, 7, 8, 9, 10}
go calculate(num1, true, chn)
go calculate(num2, false, chn)
var res1, res2 int
res1 = <- chn
res2 = <- chn
fmt.Printf("%T, %v, %T, %v ", res1, res1, res2, res2)
fmt.Println("total =", res1 + res2)
// TEST 3, close a channel
close(chn)
res, ok := <- chn
fmt.Println(res, ok)
}
func greet(name string) {
for i := 0; i < 3; i++ {
fmt.Println("Hello", name)
time.Sleep(time.Second)
}
}
func calculate(nums []int, isfast bool, chn chan int) {
var res int = 0
for _, n := range nums {
res = res + n
if isfast {
time.Sleep(time.Second)
} else {
time.Sleep(2 * time.Second)
}
}
fmt.Println("finish calculation:", isfast)
chn <- res
}
3, run “channel.go”
go run channel.go
you should get result like this:
Hello nao nao
Hello pang pamg
Hello nao nao
Hello pang pamg
Hello nao nao
Hello pang pamg
finish calculation: true
finish calculation: false
int, 15, int, 40 total = 55
0 false