channel 使用遇到的问题

云斜月 2017-08-01 11:14:48
在使用channel时,遇到两种情况,一种使用channel可以正常使用,另外一种不可用。代码如下:

package main

import "fmt"

func sum(a []int, c chan int) {
total := 0
for _, v := range a {
total += v
}
c <- total // send total to c
}

func main() {
a := []int{7, 2, 8, -9, 4, 0}

c := make(chan int)
go sum(a[:len(a)/2], c)
go sum(a[len(a)/2:], c)
x, y := <-c, <-c // receive from c

fmt.Println(x, y, x + y)
}

在此处 通道可以正常使用,未报错。
但是我 在 main中直接使用时就会报错,如下:

d := make(chan int)
d <- 2

...全文
715 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
不得闲 2017-08-10
  • 打赏
  • 举报
回复
如果使用的是无缓冲的chan,读写,必须有不同的goroutine来做处理,否则就会死掉的 应该用 go def func(chan c){ d<-c }(c) c<-2 这样就没问题了。
zealotyao 2017-08-02
  • 打赏
  • 举报
回复
你执行d <- 2这句话的时候d就会一直等待channel被关闭或者数据被读出,所以你必须再开一个协程进行channel关闭或者读出数据 package main func main() { a := make(chan int) go func() { a <- 2 }() x := <-a println(x) }
云斜月 2017-08-01
  • 打赏
  • 举报
回复
报错信息如下:

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:

2,190

社区成员

发帖
与我相关
我的任务
社区描述
go语言学习与交流版
社区管理员
  • go语言社区
  • Freeman Z
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧