3 ms·
Not true. Buffered channels are able to express semantics impossible to express with unbuffered channels. E.g. a counting semaphore. The most common buffered ch
by 4ad 9y ago
Not true. Buffered channels are able to express semantics impossible to express with unbuffered channels. E.g. a counting semaphore. The most common buffered channel buffer size is one, and the code would not be correct with either zero, or more than one. Using buffered channels in Go for their semantics instead of their performance is a very common idiom in Go. Much more common than adding buffering to channels as an optimization.
- jerf 9y agoFair enough. But it is important for people to realize that buffered channels aren't "async" channels; they're async until they fill up, at which point they resume blocking until there is a slot available. If you have some sort of channel network setup that is deadlocking with unbuffered channels and you "fix" it by adding some buffering in, unless you've got a very solid analysis as to why that buffering is correct, you haven't fixed it, you've just delayed the problem until load is higher. It's in many ways academic anyhow. Most of the tricks I've seen for buffered channels are better done some other way, and in practice I almost always use unbuffered channels. Most of the time that someone thinks they want a buffered channel because of performance issues, they're actually exactly wrong and backwards... if there is some sort of mismatch between the speed of the consumers and producers you generally want the coupling introduced by unbuffered channels, even if it is counterintuitive.
- 4ad 9y agoYes, buffered channels should almost never be used for performance reasons. Buffered channels should be used for their semantics, but in general unbuffered channels are preferred to buffered channels if possible because buffered channels cause combinatorial explosion of state, and are hard to reason about accurately.
- KMag 9y ago> Buffered channels are able to express semantics impossible to express with unbuffered channels. You can build a buffered channel from a pair of unbuffered channels with an actor/goroutine containing a buffer connected to the output of the one channel and the input of the other. Therefore, anything that can be expressed in terms of buffered channels and actors/goroutines can be expressed in terms of buffered channels and actors/goroutines. I'll grant that somethings are very tedious to express, and it's a bit of o Turing tarpit argument.