介绍后期完善…
package mainimport ("fmt""time")func main() {// main2()// main3() // 单向// main4() // 循环// main5() // selectmain6() // 利用阻塞实现同步操作}// 非缓冲通道bufferfunc main1() {ch := make(chan string)go func() {ch <- "str"}()fmt.Println(<-ch)}// 缓冲通道bufferfunc 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 := <-senderreceiver <- 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 := 0for v := range ch {res += v}fmt.Println(res)}// selectfunc 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程序员。