介绍后期完善…
package main
import (
"fmt"
"time"
)
func main() {
// main2()
// main3() // 单向
// main4() // 循环
// main5() // select
main6() // 利用阻塞实现同步操作
}
// 非缓冲通道buffer
func main1() {
ch := make(chan string)
go func() {
ch <- "str"
}()
fmt.Println(<-ch)
}
// 缓冲通道buffer
func main2() {
ch := make(chan string, 2)
ch <- "str"
fmt.Println(<-ch)
}
// receiver 只能做接收
func receive(receiver chan<- string, str string) {
receiver <- str
}
func send(sender <-chan string, receiver chan<- string) {
str := <-sender
receiver <- str
}
func main3() {
ch1 := make(chan string, 1)
ch2 := make(chan string, 1)
receive(ch1, "hello")
send(ch1, ch2)
fmt.Println(<-ch2)
}
// 循环
func main4() {
ch := make(chan int, 10)
for i := 0; i < 10; i++ {
ch <- i
}
close(ch)
res := 0
for v := range ch {
res += v
}
fmt.Println(res)
}
// select
func strworker(ch chan string) {
time.Sleep(1 * time.Second)
fmt.Println("get into strworker. . .")
ch <- "hello"
}
func intworker(ch chan int) {
time.Sleep(1 * time.Second)
fmt.Println("get into intworker. ..")
ch <- 1
}
func main5() {
chInt := make(chan int)
chStr := make(chan string)
go func() {
strworker(chStr)
}()
go func() {
intworker(chInt)
}()
for i := 0; i < 2; i++ {
select {
case <-chStr:
fmt.Println("get value from chStr")
case <-chInt:
fmt.Println("get value from chInt")
}
}
}
// 阻塞实现同步
func worker(ch chan string) {
fmt.Println("get into worker...")
ch <- "str"
}
func main6() {
ch := make(chan string)
go worker(ch)
<-ch
}
正在学习Go语言的PHP程序员。