Member-only story
When and How to Use the Go Channel
Channel == Semaphore + Buffer
Go’s concise structure and powerful native library enable us to hit the ground running easily. It is more efficient than Java or Python when implementing the same functions, especially its concurrent programming, which is very handy and widely admired due to its goroutine
and channel
.
goroutine
and channel
has much to dig into, and let’s start with channel
, which I used to consider narrowly as a message queue to transfer data between goroutines
and support data synchronization, but definitely owns a bigger stage.
Channel == Semaphore + Buffer
Channel is a data type like slice
and map
, and the equation channel == Semaphore + Buffer
reveals its essence. Semaphore is the core concept followed by the two major features, delivery guarantee, and state.
Delivery guarantee clears the way for goroutine, saving it from focusing on whether the signal can be transferred through the channel or whether the dependent channel can receive the signal but only on the logic implementation. In the example below, the delivery guarantee of ch1
and ch2
determines the success of the goroutine.
go func() {
for {
i,ok := <-ch1 // blocked if ch1 is empty
if ok {
ch2 <- i*i
} else {…