Introduction to Channels

This lesson explains how goroutines can interact with one another through channels.

Concept

Previously, the goroutines executed independently; they did not communicate. Of course, to be more useful, they have to communicate by sending and receiving information between them and, thereby, coordinating (synchronizing) their efforts. Goroutines could communicate by using shared variables, but this is highly discouraged because this way of working introduces all the difficulties with shared memory in multi-threading.

Instead, Go has a special type, the channel, which is like a conduit (a pipe) through which you can send typed values and which takes care of communication between goroutines, avoiding all the pitfalls of shared memory. The very act of communication through a channel guarantees synchronization; there is no need for explicit synchronization through locking anything.

Data is passed around on channels: only one goroutine has access to a data item at any given time: so data races cannot occur, by design. The ownership of the data (that is the ability to read and write it) is passed around. A useful analogy is to compare a channel with a conveyor belt in a factory. One machine (the producer goroutine) puts items onto the belt, and another machine (the consumer goroutine) takes them off for packaging.

Channels serve the dual purpose of communication, i.e., the exchange of value with synchronization, guaranteeing that two calculations (goroutines) are in a known state at any time.

Get hands-on with 1200+ tech skills courses.