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)
}
}
有疑问加站长微信联系(非本文作者)