小白提问:go 通道发送操作的疑惑

Orocker · · 270 次点击 · 开始浏览    置顶

代码如下: ``` package main import "fmt" func main() { ch1 := make(chan int, 1) go func() { for i := 0; i < 10; i++ { fmt.Printf("Sender: sending element %v ... \n", i) ch1 <- i } fmt.Println("Sender: close the channel") close(ch1) }() for { elem, ok := <-ch1 if !ok { fmt.Println("Receiver: closed the channel") break } fmt.Printf("Receiver: received an element%v \n", elem) } fmt.Println("End!") } ``` 输出结果: ``` Sender: sending element 0 ... Sender: sending element 1 ... Sender: sending element 2 ... Receiver: received an element0 Receiver: received an element1 Receiver: received an element2 Sender: sending element 3 ... Sender: sending element 4 ... Sender: sending element 5 ... Receiver: received an element3 Receiver: received an element4 Receiver: received an element5 Sender: sending element 6 ... Sender: sending element 7 ... Sender: sending element 8 ... Receiver: received an element6 Receiver: received an element7 Receiver: received an element8 Sender: sending element 9 ... Sender: close the channel Receiver: received an element9 Receiver: closed the channel End! ``` 我的问题是为什么一次能发3个元素,但通道的缓冲区只设置为了1啊,是因为go func(){}()开启了3个goroutine吗? 麻烦解答一下,谢谢

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

270 次点击  
加入收藏 微博
2 回复  |  直到 2021-02-05 15:39:28
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传