doutan5337 2015-12-25 14:47
浏览 23

发送到频道的消息会丢失吗?

The question is in the title. Let's say I have several goroutines (more than 100) all of which eventually send data to one chan (name it mychan := make(chan int)) One another goroutine does <- mychan in an endless for loop Is it okay or the chan can happen to lose some data? Should I use buffered chan instead? Or perhaps I am to create a chan and a "demon" goroutine that will extract message for each worker goroutine?

  • 写回答

3条回答 默认 最新

  • duai0935 2015-12-25 15:37
    关注

    No, they can't be lost.

    While the language spec does not in any way impose any particular implementation on channels, you can think of them as critical sections or mutexes protecting either a single value (for the single message) or an array/list of them (for buffered channels).

    The semantics are then enforced in such a way that as soon as a goroutine wants to send a message to a channel, it enters that critical section / locks the mutex, and then either succeds at sending—there's a free slot for its message—or blocks—when there isn't. As soon as such a slot appears—someone has received an existing message—the sending succeeds and the sending goroutine gets unblocked.

    This is a simplified explanation but I hope it gets you the correct idea. In other words, channels in Go is not like message queues which usually are happy with losing messages.

    On a side note, I'm not really sure what happens if the receiver panics in some specific state when it's about to receive your message. IOW I'm not sure whether Go guarantees that the message is either sent or not in the presence of a receiver panicking in an unfortunate moment.

    Oh, and there's that grey area of the main goroutine exiting (that one running the main.main() function): the spec states clear than the main goroutine does not wait for any other goroutines to complete when it exits. So unless you somehow arrange for the synchronized controlled shutdown of all your spawned goroutines, I beleive they may lose messages. On the other hand, in this case the world is collapsing anyway…

    评论

报告相同问题?

悬赏问题

  • ¥20 Java-Oj-桌布的计算
  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路