Synchronization of goroutines
Explore how to synchronize goroutines in Go by using channels to signal completion and detect closed channels. Learn techniques such as closing channels properly, the comma-ok operator for receiving, and the producer-consumer pattern with buffered channels to manage blocking and concurrency efficiently.
We'll cover the following...
Channels can be closed explicitly. However, they are not like files. You don’t usually need to close them. Closing a channel is only necessary when the receiver must be told that there are no more values coming. Only the sender should close a channel, never the receiver.
Closing a channel
The question is, how can we signal when sendData() is done with the channel, and how can getData() detect that the channel whether closed or blocked?
Signaling
This is done with the function close(ch). This marks the channel as unable to accept more values through a send operation <-. Sending to or closing a closed channel causes a run-time panic. It is good practice to do this with a defer statement immediately after the making of the channel (when it is appropriate in the given situation):
ch := ...