gpt4 book ai didi

go - 缓冲 channel 是否维持秩序?

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

在 Go 中,缓冲 channel 是否有顺序保证?

例如:你有两个 goroutines A & B 共享一个 channel 。 A 将数据推送到 channel 上,而 B 从中读取数据。你保证 B 会按照 A 放入 channel 的相同顺序读取数据吗?

我知道如果有多个生产者或消费者,顺序可能是不确定的,但我特别想问的是只有 1 个生产者和 1 个消费者。

最佳答案

"Are you guaranteed that B will read data In the same order that A put it into the channel?"

是的。保证数据的顺序。
但是交付仅对无缓冲 channel 有保证,没有缓冲。
(请参阅此答案的第二部分)


您可以从 The Nature Of Channels In Go 中看到“William Kennedy”中说明的 channel 概念。 (2014 年 2 月):它显示了如何遵守顺序或读/写。
另见 Channels :

Receivers always block until there is data to receive.

  • If the channel is unbuffered, the sender blocks until the receiver has received the value.
  • If the channel has a buffer, the sender blocks only until the value has been copied to the buffer; if the buffer is full, this means waiting until some receiver has retrieved a value.

无缓冲 channel

https://www.ardanlabs.com/images/goinggo/Screen+Shot+2014-02-16+at+10.10.54+AM.png

缓冲 channel

https://www.ardanlabs.com/images/goinggo/Screen+Shot+2014-02-17+at+8.38.15+AM.png

图片来源:Ardan labs - William Kennedy


同一位 William Kennedy 在“ The Behavior Of Channels ”(2017 年 10 月)中详细介绍了交付保证方面的内容

Do I need a guarantee that the signal sent by a particular goroutine has been received?

https://www.ardanlabs.com/images/goinggo/86_signaling_with_data.png

图片来源:同样,Ardan labs - William Kennedy

The three channel options are Unbuffered, Buffered >1 or Buffered =1.

  • Guarantee

    • An Unbuffered channel gives you a Guarantee that a signal being sent has been received.
      • Because the Receive of the signal Happens Before the Send of the signal completes.
  • No Guarantee

    • A Buffered channel of size >1 gives you No Guarantee that a signal being sent has been received.
      • Because the Send of the signal Happens Before the Receive of the signal completes.
  • Delayed Guarantee

    • A Buffered channel of size =1 gives you a Delayed Guarantee. It can guarantee that the previous signal that was sent has been received.
      • Because the Receive of the First Signal, Happens Before the Send of the Second Signal completes.

关于go - 缓冲 channel 是否维持秩序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25795131/

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