Channels
A channel is a typed conduit/tube through which we send and receive values with the channel operator <-
.
The data flows in the direction of the arrow <-
We can create channels similar to creating maps and slices using the make
function:
By default, sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit locks or condition variables.
Example
The example code sums the numbers in a slice, distributing the work between two goroutines. Once both goroutines have completed their computation, it calculates the final result.
Buffered Channels
Channels can be buffered. Provide the buffer length as the second argument to make
to initialize a buffered channel:
Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.
Example
If we overfill the buffer using the commented code on line 9, we would get: fatal error: all goroutine are asleep - deadlock!
Last updated