缓冲通道在Go语言中的用途是什么?

huangapple go评论99阅读模式
英文:

What is the use of buffered channels in Go?

问题

我理解了你的问题。根据你提供的链接和代码,如果通道是带缓冲的,它不会阻塞。

但是我不明白它的用途是什么。假设我有两个goroutine,第一个goroutine接收data1,第二个goroutine接收data2,那么它将阻塞直到有其他子例程可以处理data3。

我不明白这有什么区别?即使没有缓冲区,它也会以相同的方式执行。你能解释一种可能的情况,缓冲区是有用的吗?

英文:

I understand from this question "https://stackoverflow.com/questions/11943841/golang-what-is-channel-buffer-size" that if the channel is buffered it won't block.

c := make(chan int, 1)
c <- data1 // doesn't block
c <- data2 // blocks until another goroutine receives from the channel
c <- data3
c <- data4

But I don't understand whats the use of it. Suppose if I have 2 goroutines, 1st one will received data1 and 2nd one receives data2 then it will block till any subroutines gets free to process data3.

I don't understand what difference did it make ? It would have executed the same way without buffer. Can you explain a possible scenario where buffering is useful ?

答案1

得分: 9

一个带缓冲的通道允许向其中添加数据的 goroutine 继续运行和执行其他任务,即使从通道中读取数据的 goroutine 稍微滞后了一点。

例如,你可能有一个 goroutine 负责接收 HTTP 请求,并且你希望它尽可能快地处理请求。然而,你也希望它能够将一些后台任务排队,比如发送电子邮件,这可能需要一些时间。因此,HTTP 的 goroutine 只需解析用户的请求,并快速将后台任务添加到带缓冲的通道中。其他的 goroutine 会在有空闲时处理这些任务。如果你的 HTTP 请求突然激增,只要缓冲区足够大,用户就不会注意到 HTTP 的处理速度变慢。

英文:

A buffered channel allows the goroutine that is adding data to the buffered channel to keep running and doing things, even if the goroutines reading from the channel are starting to fall behind a little bit.

For example, you might have one goroutine that is receiving HTTP requests and you want it to be as fast as possible. However you also want it to queue up some background job, like sending an email, which could take a while. So the HTTP goroutine just parses the user's request and quickly adds the background job to the buffered channel. The other goroutines will process it when they have time. If you get a sudden surge in HTTP requests, the users will not notice any slowness in the HTTP if your buffer is big enough.

答案2

得分: 1

这个网站有一个很好的解释:

https://www.openmymind.net/Introduction-To-Go-Buffered-Channels/

英文:

This site has a good explanation:

https://www.openmymind.net/Introduction-To-Go-Buffered-Channels/

huangapple
  • 本文由 发表于 2014年3月31日 02:03:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/22747711.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定