SoFunction
Updated on 2025-03-04

Detailed explanation of the advanced usage of Channel in Golang

In reading the source code of k8s, I found some interesting uses.

In Go,chan(Channel) is a mechanism used to communicate between different goroutines.WaitForCacheSync(stopCh <-chan struct{}) errorParameters in the methodstopCh <-chan struct{}Indicates a read-only channel for receiving a stop signal.

The basic concept of channel

  • Channel: Channel is a data structure in Go language used to pass data between different goroutines. The channel can be unbuffered (synchronous) or buffered (asynchronous).
  • Read-only channel<-chan TRepresents a read-only channel, which means that you can only receive data from this channel, but cannot send data to this channel.
  • Write only channelchan<- TIndicates a write-only channel, which means that you can only send data to this channel, but cannot receive data from this channel.

stopCh in WaitForCacheSync method

WaitForCacheSyncMethods are usually used to wait for caches (such as Informer cache in Kubernetes) to complete synchronously.stopChThe parameter is a read-only channel that receives a stop signal to interrupt the waiting process if needed.

Parameter explanation

  • stopCh <-chan struct{}: This is a read-only channel with typestruct{}struct{}is a zero-size structure type that is usually used to represent signals or events because it does not take up any memory.

Use scenarios

  • Stop signalstopChChannels are usually used to receive stop signals. When you send a value to this channel, it means you want to stop the current operation.
  • Inter-coroutine communication:passstopChChannels, different goroutines can work together. For example, one goroutine can wait for the cache synchronization to complete, while another goroutine can send a stop signal if needed.

Sample code

Here is a simple example showing how to use itstopChChannel to controlWaitForCacheSyncMethod execution:

package main
 
import (
	"fmt"
	"time"
)
 
// WaitForCacheSync simulates the method of waiting for cache synchronizationfunc WaitForCacheSync(stopCh &lt;-chan struct{}) error {
	("Waiting for cache to sync...")
 
	select {
	case &lt;-(5 * ):
		("Cache synced successfully.")
		return nil
	case &lt;-stopCh:
		("Received stop signal, stopping cache sync.")
		return ("cache sync stopped")
	}
}
 
func main() {
	stopCh := make(chan struct{})
 
	// Start a goroutine to wait for cache synchronization	go func() {
		err := WaitForCacheSync(stopCh)
		if err != nil {
			("Error:", err)
		}
	}()
 
	// Simulate some work	(2 * )
 
	// Send a stop signal	close(stopCh)
 
	// Wait for a while to observe the output	(3 * )
}

Code explanation

  • definitionWaitForCacheSyncmethod
func WaitForCacheSync(stopCh <-chan struct{}) error {
    ("Waiting for cache to sync...")
 
    select {
    case <-(5 * ):
        ("Cache synced successfully.")
        return nil
    case <-stopCh:
        ("Received stop signal, stopping cache sync.")
        return ("cache sync stopped")
    }
}
    • useselectThe statement waits for two events: the cache synchronization is completed (modified after 5 seconds) or the stop signal is received.
    • If a stop signal is received, an error is returned.
  • existmainUsed in functionsstopChaisle

func main() {
    stopCh := make(chan struct{})
 
    // Start a goroutine to wait for cache synchronization    go func() {
        err := WaitForCacheSync(stopCh)
        if err != nil {
            ("Error:", err)
        }
    }()
 
    // Simulate some work    (2 * )
 
    // Send a stop signal    close(stopCh)
 
    // Wait for a while to observe the output    (3 * )
}
  • Create astopChaisle.
  • Start a goroutine to callWaitForCacheSyncmethod.
  • After simulating some work, send a stop signal (close the channel).
  • Wait for a while to observe the output.

In this way, you can usestopChChannel to controlWaitForCacheSyncThe execution of the method ensures that the waiting process can be interrupted if needed.

The above is a detailed explanation of the advanced usage of Channel in Golang. For more information on the usage of Golang Channel, please follow my other related articles!