- Used for synchronization and communication between go routines without explicit locks or condition variables Internally, works like a FIFO circular queue
- Channels transfer the copy of the object.
- By default, sends and receives block until the other side is ready. This allows go-routines to synchronise without explicit locks or condition variables.
- Sends to a buffered channel block only when the buffer is full. Receives block when the buffer is empty.
- zero-value of a channel is nil
- When a go-routine G1 wants to receive data from another go-routine G2, but G2 never sends the data, then the channel will make G1 to wait indefinitely, and vice versa.
- If the buffer is full or if there is nothing to receive, a buffered channel will behave very much like an unbuffered channel.
- For unbuffered channel, one go-routine should be in running state, while other go-routine should be in runnable state.
- the send and receive action need to acquire the lock on the channel
- The only shared memory between go-routines access is
hchanwhich is protected bymutex. - the task is copied from/to the channel
type hchan struct {
qcount uint // total data in the queue
dataqsiz uint // size of the circular queue
buf unsafe.Pointer // pointer to an array(queue), and is nil for unbuffered channel
elemsize uint16
closed uint32 // if channel is closed
elemtype *_type // element type
sendx uint // send index
recvx uint // receive index
recvq waitq // list of recv waiters (doubly linked list)
sendq waitq // list of send waiters (doubly linked list)
lock mutex // mutex for concurrent access to the channel
}