gpt4 book ai didi

go - 发送到 channel 的消息会丢失吗?

转载 作者:IT王子 更新时间:2023-10-29 01:06:08 25 4
gpt4 key购买 nike

问题在标题中。假设我有几个 goroutine(超过 100 个),所有这些 goroutine 最终都将数据发送到一个 chan(将其命名为 mychan := make(chan int))另一个 goroutine 执行 <- mychan在无休止的 for 循环中 可以吗,还是 chan 会丢失一些数据?我应该改用 buffered chan 吗?或者我可能要创建一个 chan 和一个“恶魔”goroutine 来为每个 worker goroutine 提取消息?

最佳答案

如果某些东西已成功发送到 channel 中,那么不会,它不会在正确的工作环境中丢失(我的意思是如果你正在篡改你的内存或者你由于宇宙射线而发生位翻转那么不要指望当然是任何东西)。

ch <- x时消息发送成功返回。否则,如果它发生 panic ,它并没有真正被发送,如果你没有恢复,你可以声称它丢失了(但是,由于应用程序逻辑,它会丢失)。如果 channel 关闭或内存不足,可能会发生 panic 。

类似地,如果发送方以非阻塞模式(通过使用选择)放入 channel ,您的 channel 中应该有足够的缓冲区,因为消息可能会“丢失”(尽管是故意的)。例如 signal.Notify 以这种方式工作:

Package signal will not block sending to c: the caller must ensure that c has sufficient buffer space to keep up with the expected signal rate.

关于go - 发送到 channel 的消息会丢失吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34463793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com