func Hello(a chan bool) {
fmt.Println("In the Hello function")
a <- true
}
fmt.Println("Main initialized!")
func main() {
a := make(chan bool)
go Hello(a)
if <-a {
fmt.Println("The hello run successfully")
} else {
fmt.Println("Hello error")
}
}
// Main initialized!
// In the Hello function
// The hello run successfully
package main
import (
"fmt"
)
func producer(chnl chan int) {
for i := 0; i < 10; i++ {
chnl <- i
}
close(chnl)
}
func main() {
ch := make(chan int)
go producer(ch)
for {
v, ok := <-ch
if ok == false {
break
}
fmt.Println("Received ", v, ok)
}
}
使用接收状态和for循环,可以优化前面的square.go代码.
package main
import (
"fmt"
)
// extract common digit operation from the two function
func DigitOps(num int, digitch chan int) {
for num != 0 {
digit := num % 10
num /= 10
digitch <- digit
}
close(digitch)
}
// go routine to compute cube
func ComCubes(num int, cubeop chan int) {
sum := 0
digitch := make(chan int)
go DigitOps(num, digitch)
for digit := range digitch {
sum += digit * digit * digit
}
cubeop <- sum
}
// go routine to compute square
func ComSquare(num int, squareop chan int) {
sum := 0
sch := make(chan int)
go DigitOps(num, sch)
for d := range sch {
sum += d * d
}
squareop <- sum
}
func main () {
//test for compute square + cube
num := 123
squc := make(chan int)
cubech := make(chan int)
go ComCubes(num, cubech)
go ComSquare(num, squc)
squares, cubes := <-squc, <-cubech
fmt.Println("Final output:", squares + cubes)
}
package main
import (
"fmt"
"time"
)
func write(ch chan int) {
for i := 0; i < 5; i++ {
ch <- i
fmt.Println("successfully wrote", i, "to ch")
}
close(ch)
}
func main() {
ch := make(chan int, 2)
go write(ch)
// time.Sleep(2 * time.Second)
for v := range ch {
fmt.Println("read value", v,"from ch")
time.Sleep(2 * time.Second)
}
}
/*
output:
successfully wrote 0 to ch
successfully wrote 1 to ch
read value 0 from ch
successfully wrote 2 to ch
read value 1 from ch
successfully wrote 3 to ch
read value 2 from ch
successfully wrote 4 to ch
read value 3 from ch
read value 4 from ch
*/