dongmie3526 2014-08-28 02:10
浏览 30
已采纳

去通道容量,为什么要比我指定的多一个元素

package main
import "fmt"
import "time"

func main() {
     message := make(chan string ,1) // no buffer
     count := 3

     go func() {
          for i := 1; i <= count; i++ {
               fmt.Println("send message")
               message <- fmt.Sprintf("message %d", i)
          }
     }()

     time.Sleep(time.Second * 3)

     for i := 1; i <= count; i++ {
          fmt.Println(<-message)
     }
}

The output is

send message
send message  [wait for 3 sec]
message 1
send message
message 2
message 3

If I change message := make(chan string ,1) // no buffer to

message := make(chan string ,2) // no buffer

I got

send message
send message
send message [wait 3 sec]
message 1
message 2
message 3

Why 2 buffers channel can store 3 string objects? not 2?

thanks,

  • 写回答

1条回答 默认 最新

  • doujiao2014 2014-08-28 02:21
    关注

    It works like this because the buffer holds N messages before it blocks. When the N+1 messages comes in GO will see that it exceeds the capacity you specified and will have to block, waiting for something to take from that channel. When passing a buffer size the sender will always block on N+1 message.

    So for instance with size 2 you have an empty buffer:

    [][]

    Then a message comes in, is put in the buffer:

    [m1][]

    Then another one, we can keep on going because we have space in the buffer

    [m1][m2]

    Then another comes in, ups we don't have more space in the buffer so we block

    [m1][m2]m3 -> block

    Something like this.

    The size is basically the number of messages that can be sent to the buffer without blocking.

    For the future I recommend http://golang.org/doc/effective_go.html#channels

    var sem = make(chan int, MaxOutstanding)
    

    Once MaxOutstanding handlers are executing process, any more will block trying to send into the filled channel buffer, until one of the existing handlers finishes and receives from the buffer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制