Interview Question
This is a classic Golang interview question that tests your understanding of channels. The requirements are as follows:
- Start three goroutines.
- The three goroutines must print
cat dog fish cat dog fish...in sequence. - Each goroutine must print 100 times, for a total of 300 outputs.
Implementation Approach
We will refer to the three goroutines as g0, g1, and g2. Since they must print alternately in sequence, when g0 is running, g1 and g2 need to block and wait. After g0 finishes, it must notify g1 to run. After g1 finishes, it must notify g2, and so on.
We know that receiving a message from an unbuffered channel, or from a buffered channel whose buffer is empty, causes the goroutine to block and wait. Therefore, we can pass two channels to each printing goroutine: one for receiving a signal to execute, and another for notifying the next goroutine to execute.
At the same time, we can use a sync.waitGroup to block the main goroutine until all child goroutines have finished.
Implementation Code
| |
Code Execution
The output is as follows:

Further Considerations
In the code above, can the following three lines be changed to initialize unbuffered channels? If not, why?
| |
(The End)