本文主要是介绍go | channel direction、channel sync、channelbuffer,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
go 中的管道通信
管道通信直连,管道的特点就是单工,一方只能接受/发送
package main
import ("fmt"
)func ping(pings chan<- string, msg string){pings <- msg
}/*函数pong中 参数pings 是一个接收通道(只能从管道接收数据)参数pongs 是一个发送通道(只能发送数据给管道)<- 在最前头就是发送,反之就是接收
*/
func pong(pings <-chan string, pongs chan<- string){/* msg := <- pingspong <- msg*/msg := <-pings // pong函数从只接收通道接收数据 pongs <- msg // 然后向只发送通道发送数据
}func main(){pings := make(chan string, 1)pongs := make(chan string, 1)ping(pings, "hello world ! my name is zhangbuda ...")pong(pings, pongs)fmt.Println(<- pongs)
}
#运行结果
hello world ! my name is zhangbuda ...
go 的管道通信,同步
package main
import ("fmt""time"
)
func worker(done chan bool){fmt.Println("working ...")time.Sleep(time.Second *2)fmt.Println("work done ...")done <- true
}/*实现管道通信同步
*/
func main(){done := make(chan bool, 1)go worker(done)flag := false flag = <- doneif flag {fmt.Println("the main func is end ...")}}
#运行结果
working ...
work done ...
the main func is end ...
管道缓冲
package main
import ("fmt"
)func main(){message := make(chan string, 5)message <- "hello world..."message <- "my name is zhangbuda!!!"message <- "how are you?"message <- "are you fine?"message <- "yeah, I'm fine!!"for i:=0; i < 5; i++{fmt.Println(<-message)}
}
#运行结果
hello world...
my name is zhangbuda!!!
how are you?
are you fine?
yeah, I'm fine!!
这篇关于go | channel direction、channel sync、channelbuffer的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!