Golang中通道缓冲容量0和1之间的差异
I have set channel buffer size to zero, like var intChannelZero = make(chan int)
, when getting value from the intChannelZero
will be blocked until the intChannelZero
has value.
Also, I set channel buffer size to one, like var intChannelOne = make(chan int, 1)
, when getting value from the intChannelOne
will be blocked until the intChannelOne
has value.
We know the capacity of intChannelZero
is zero, the capacity of intChannelOne
is one, so I want to know:
- When putting a value to the
intChannelZero
likeintChannelZero <- 1
, where the value be saved? - The differences between
intChannelZero
andintChannelOne
when putting a value to them.
Who can explain it at the level of Golang Runtime Enviroment? Thanks a lot.
If the channel is unbuffered (capacity is zero), then communication succeeds only when the sender and receiver are both ready.
If the channel is buffered (capacity >= 1), then send succeeds without blocking if the channel is not full and receive succeeds without blocking if the buffer is not empty.
When putting a value to the intChannelZero like intChannelZero <- 1, where the value be saved?
The value is copied from the sender to the receiver. The value is not saved anywhere other than whatever temporary variables the implementation might use.
The differences between intChannelZero and intChannelOne when putting a value to them.
Send on intChannelZero blocks until a receiver is ready.
Send on intChannelOne blocks until space is available in the buffer.
Both unbuffered and buffered channel differences will be in terms of,
- Sends to channel is blocked
- Receives from channel is blocked
For unbuffered channels
Sends will be blocked if the channel already send a message and hasn't yet been received.
Receives will be blocked if no sends ever happened.
For buffered channels
Sends will be blocked if already n(channel size) sends happened and none of them received. ie entire channel size has been used by messages send but nothing was received.
Receives will be blocked if the buffer is empty ie doesn't have any unconsumed sends
Runtime errors
Receive blocked will throw the bellow error
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan receive]:
Send blocked will throw the bellow error
fatal error: all goroutines are asleep - deadlock!
goroutine 1 [chan send]: