It provides a connection between two goroutines, allowing them to communicate (sends value to another)
By default (unbuffered), sends and receives block until the other side is ready. This allows goroutines to synchronize without explicit Lock or condition variables. (Go sync)
- Note: Only the sender should close a channel, never the receiver. Sending on a closed channel will cause a panic.
- Note: Channels aren’t like files; you don’t usually need to close them. Closing is only necessary when the receiver must be told there are no more values coming, such as to terminate a
Buffered vs Unbuffered
- Unbuffered channels block the sender until the receiver receives the data, and vice versa. So you need another Goroutine to cooperate with.
- Buffered channels, on the other hand, are non-blocking for the sender as long as there is still room in the buffer.
select statement lets a goroutine wait on multiple communication operations (handle multiple channels).
select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.
default case in a
select is run if no other case is ready.
Set timeout by
Channel VS Mutex
- passing ownership of data
- distributing units of work
- communicating async results