channels 在Golang中是一个具有类型的管道(conduit)
Channels are a typed conduit through which you can send and receive values with the channel operator, <-.
创建管道的方式很简单:
ch := make(chan int) // declare a channel of type int ch := make(chan int, 100) // buffered channels // Sends to a buffered channel block only when the buffer is full. // Receives block when the buffer is empty. v, ok := <-ch // ok is false if there are no more values to receive and the channel is closed.
当所有的 gorountine 都处于 asleep 状态的时候,程序报错。
我感觉Golang里的 channels 就类似于Python标准库的queue.Queue,但是比Python要安全和智能。
关闭管道,使用close函数。
循环 for i := range c 从管道中接收值直到管道被关闭。
下面是一个例子:
一个线程不断生成 fibonacci 数列,另一个线程不断去输出,两个线程用 channels 通信package main import ( "fmt" ) func fibonacci(n int, c chan int) { x, y := 1, 1 for i := 0; i < n; i++ { c <- x x, y = y, x+y } close(c) } func main() { c := make(chan int, 10) go fibonacci(cap(c), c) for i := range c { fmt.Println(i) } }
计算[0, 1000)的和,10个线程每个线程计算一部分,最后主线程计算总和。
package main import "fmt" func main() { c := make(chan int) for i := 0; i < 100; i += 10 { go func (a int, c chan int) { s := 0 for i := a; i < a + 10; i++ { s += i } c <- s }(i, c) } sum, i := 0, 0 for v := range c { sum += v i++ if i == 10 { close(c) } } fmt.Println(sum) }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)