golang中channel的用法
2018-04-01 14:05
344 查看
go语言的range循环可以直接在channels上面迭代。使用range循环一次从channel中接受数据,当channel被关闭并且没有值可接受时跳出循坏。
双向channel可以隐式转换为单向channel,反之不行
多个goroutines并发地向同一个channel发送数据,返回最快响应的,此时应该采用有缓冲的channel,否则,其他goroutine返回之后没有通道接受,则产生goroutine卡死,泄露
func main() { natures := make(chan int) squares := make(chan int) go func() { for x := 0; x < 100; x++ { natures <- x } close(natures) }() go func() { for x := range natures { squares <- x * x } close(squares) }() for x := range squares { fmt.Println(x) } }
双向channel可以隐式转换为单向channel,反之不行
func main() { natures := make(chan int) squares := make(chan int) go counter(natures) go squar(natures,squares) printer(squares) } func squar(in <-chan int,out chan<- int) { for i:= range in { out <- i*i } close(out) } func printer(in <-chan int) { for i := range in { fmt.Println(i) } } func counter(out chan<- int) { for i:=0;i<100;i++ { out <- i } close(out) }
多个goroutines并发地向同一个channel发送数据,返回最快响应的,此时应该采用有缓冲的channel,否则,其他goroutine返回之后没有通道接受,则产生goroutine卡死,泄露
func mirroredQuery() string { responses := make(chan string, 3) go func() { responses <- request("asia.gopl.io") }() go func() { responses <- request("europe.gopl.io") }() go func() { responses <- request("americas.gopl.io") }() return <-responses // return the quickest response }
相关文章推荐
- 【转】golang的channel的几种用法
- Golang channel用法
- Golang Channel用法简编
- Golang Channel用法简编
- Golang Channel用法简编
- Golang Channel用法简编
- Golang Channel用法简编
- Golang channel select用法
- Golang Channel用法简编
- golang语言中for循环语句用法实例
- Golang从入门到精通(十九):Golang并发编程之Channel
- golang中的channel
- golang中recover和panic用法, goland里的try catch
- golang中net包用法(二)--IP
- golang中image/draw包用法
- Java 复制大文件方式FileChannel 用法
- Golang, 以17个简短代码片段,切底弄懂 channel 基础
- golang channel阻塞问题解决
- golang语言并发与并行——goroutine和channel的详细理解
- Golang的select多路复用以及channel使用实践