japananh / TIL

Today I learned

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Buffered vs Unbuffered channel in Golang

japananh opened this issue · comments

Feature Unbuffered Channel Buffered Channel
Definition No storage, transfers data directly between goroutines. Contains a buffer, allowing storage of multiple values.
Capacity 0 (zero) >= 1 (defined at creation)
Creation ch := make(chan int) ch := make(chan int, bufferSize)
Behavior (Send operation) Will block until the sent value is received by another goroutine. Will send immediately if the buffer has space, or else it will block.
Behavior (Receive operation) Will block until a value is sent by another goroutine. Will receive immediately if the buffer has values, or else it will block.
Use Case - Real-time processes where immediate handling is crucial.
- Ensuring step-by-step synchronization between goroutines.
- Situations where senders might momentarily produce data faster than receivers can handle.
- When you want some "elasticity" between producers and consumers of data.
Synchronization Synchronization is direct. When one goroutine sends a value on the channel, it blocks until another goroutine receives that value. This ensures direct hand-off between the sender and the receiver, which can be thought of as a form of strict synchronization. Depends on buffer's state:
For send operation:
- If the buffer is not full, a goroutine can send a value to the channel without blocking. The value goes into the buffer.
- If the buffer is full, the sending goroutine will block until there is space in the buffer (i.e. until some other goroutine receives a value from the channel).
For receive operation:
- If the buffer is not empty, a goroutine can receive a value from the channel without blocking.
- If the buffer is empty, the receiving goroutine will block until there is a value in the buffer (i.e., some other goroutine sends a value to the channel).