func chanDemo(){
// var c chan int
//定义 c 类型是 chan int 此时为 nil
c := make(chan int)
c <- 1
c <- 2
n := <-c
fmt.Println(n)
}
atal error: all goroutines are asleep - deadlock!
运行上面的代码为什么会是 deadlock,这是因为 channel 是 goroutine 和 goroutine 之间通道,这个通道进行发送,如果没有其他通道进行接收就会发生 deadlock。
func chanDemo(){
// var c chan int
//定义 c 类型是 chan int 此时为 nil
c := make(chan int)
go func(){
for{
n := <-c
fmt.Println(n)
}
}()
c <- 1
c <- 2
}
func main() {
chanDemo()
}
这样我们通过匿名函数创建 goroutine 来接受 channel 发送数据,就不会造成 deadlock。在 go 语言中 channel 和 function 一样都是一等公民,我们这里 channel 作为参数和返回值来使用。
go func(){
for{
n := <-c
fmt.Println(n)
}
}()
这里 func() 是一个匿名函数作为闭包使用,闭包是可以访问到其环境变量 c 的。我们可让 c 作为参数传入。
func worker(c chan int){
for{
n := <-c
fmt.Println(n)
}
}
func chanDemo(){
// var c chan int
//定义 c 类型是 chan int 此时为 nil
c := make(chan int)
go worker(c)
c <- 1
c <- 2
}
进行改造,将匿名函数提出为 worker 然后将 c 作为参数传入 worker 进行使用。在 worker 中我们接受 channel 发送数据。
func worker(id int,c chan int){
for{
fmt.Printf("Worker %d received %c\n",id,<-c)
}
}
func chanDemo(){
// var c chan int
//定义 c 类型是 chan int 此时为 nil
var channels [10]chan int
for i:= 0; i < 10; i++{
channels[i] = make(chan int)
go worker(i,channels[i])
}
for i := 0; i < 10; i++{
channels[i] <- 'a' + i
}
time.Sleep(time.Millisecond)
}
我们可创建 chan 的集合,然后遍历出 10 chan 可以作为参数传入到 worker 中使用,这次我们一次就创建了 10 chan 来用于接受数据,然后再为 worker 添加一个参数作为 channel 的 id 来表示 channel。
Worker 0 received a
Worker 2 received c
Worker 3 received d
Worker 5 received f
Worker 6 received g
Worker 7 received h
Worker 8 received i
Worker 4 received e
for i := 0; i < 10; i++{
channels[i] <- 'a' + i
}
for i := 0; i < 10; i++{
channels[i] <- 'A' + i
}
我们可以做个遍历来想channel 传入数据,用于接受。
Worker 9 received j
Worker 5 received f
Worker 6 received g
Worker 0 received a
Worker 0 received A
Worker 1 received b
Worker 1 received B
Worker 7 received h
Worker 2 received c
Worker 2 received C
Worker 8 received i
Worker 3 received d
Worker 6 received G
Worker 3 received D
Worker 5 received F
Worker 9 received J
Worker 8 received I
Worker 4 received E
Worker 7 received H
这里顺序是乱的,在 workder 虽然接受是按顺序的,但是随后的 fmt.Printf 是 IO 操作。goroutine 会进行调度,调度之后有可能会发送顺序乱。
我们的 channel 还可以作为返回值来使用,现在创建一个 createWorker 这个函数可以返回一个 chan
func createWorker(id int ) chan int{
c := make(chan int)
go func(){
for{
fmt.Printf("Worker %d received %c\n",id,<-c)
}
}()
return c
}
var channels [10]chan int
for i:= 0; i < 10; i++{
channels[i] = createWorker(i)
}
有疑问加站长微信联系(非本文作者)