𝗠𝗮𝘀𝘁𝗲𝗿 𝗚𝗼 𝗖𝗼𝗻𝗰𝘂𝗿𝗿𝗲𝗻𝗰𝘆 𝗪𝗶𝘁𝗵 𝗖𝗵𝗮𝗻𝗻𝗲𝗹𝘀
I once built an image processing pipeline in Go.
I used goroutines for every step. I linked them with channels. I hit run.
The program froze. Memory usage climbed. Then it died. There were no errors. There was only silence.
I wasted hours debugging a broken scheduler. I was wrong. I did not understand how channels work.
Here are three rules to stop your Go programs from hanging.
- Nil channels are black holes A nil channel blocks forever. If you send or receive on a nil channel, the goroutine stays stuck.
- Always initialize your channels with make.
- Use a nil check if you are unsure.
- Closing rules prevent panics Closing a channel is permanent.
- Only the sender should close a channel.
- Sending data to a closed channel causes a panic.
- Use the second return value to check if a channel is closed: v, ok := <-ch.
- If ok is false, the channel is closed.
- Use channel directions for safety Go lets you specify if a channel is for sending or receiving.
- chan<- int means you can only send data.
- <-chan int means you can only receive data.
- This forces the compiler to catch mistakes before you run your code.
How to build a clean pipeline:
- Use defer close to ensure a channel closes exactly once.
- Use range to loop over channels. This stops automatically when the channel closes.
- Assign direction types to your functions to create strict contracts.
When you follow these patterns, you prevent leaks and panics. You build systems that are easy to test and robust.
Your challenge: Write a function that merges multiple input channels into one output channel. Use a select loop. Add a 500ms timeout. Ensure no goroutines leak.
Post your solution in the comments.