Explain the usage of channel in golang

Time:2021-3-2

If goroutine is the concurrency of go language programs, then channels is the communication mechanism between them. A channel is a communication mechanism that allows one goroutine to send value information to another.

1 create channel

Each channel has a special type, that is, the type that channels can send data. One can send int type data
The channel of is usually written as channel int. Using the built-in make function, if the second parameter is greater than 0, it means creating a channel with cache.


ch := make(chan int) // ch has type 'chan int'
ch = make(chan int, 3) // buffered channel with capacity 3

2 channel sending and receiving

A send statement sends a value from one goroutine through channel to another goroutine that performs a receive operation. Both send and receive operations use the < – operator. In the send statement, the < – Operator splits the channel and the value to be sent. In the receive statement, the < – operator is written before the channel object. A receive operation that does not use the received result is also legal.


ch <- x
// a send statement
x = <-ch // a receive expression in an assignment statement
<-ch
// a receive statement; result is discarded

3 channel close

The channel also supports the close operation, which is used to close the channel. Any subsequent send operation based on the channel will cause a panic exception. Receiving a channel that has been closed can still receive the data that has been successfully sent before. If there is no data in the channel, a zero value data will be generated. You can close a channel by using the built-in close function


close(ch)

4 channels without cache

A send operation based on uncached channels will cause the sender goroutine to block until another goroutine performs a receive operation on the same channels. When the sent value is successfully transmitted through channels, the two goroutines can continue to execute the following statements. Conversely, if the receive operation occurs first, the receiver goroutine will block until another goroutine performs the send operation on the same channels.
Sending and receiving operations based on uncached channels will cause two goroutines to do a synchronization operation. For this reason, uncached channels are sometimes referred to as synchronous channels.

5 Series channels

Channels can also be used to connect multiple goroutines, with the output of one channel as the input of the next. This kind of serial channels is called pipeline.


func main() {
	naturals := make(chan int)
	squares := make(chan int)
	// Counter
	go func() {
		for x := 0; x < 100; x++ {
			naturals <- x
		}
		close(naturals)
	}()
	// Squarer
	go func() {
		for x := range naturals {
			squares <- x * x
		}
		close(squares)
	}()
	// Printer (in main goroutine)
	for x := range squares {
		fmt.Println(x)
	}
}

When the data that has been sent in a closed channel is successfully received, the subsequent receiving operations will not be blocked, and they will immediately return a value of zero.
The range loop of go can be iterated directly on channels. Use the range loop to receive data from the channel in turn, and jump out of the loop when the channel is closed and there is no value to receive.

6 unidirectional channels

In order to prevent abuse, the type system of go language provides one-way channel types, which are used for send only or receive only channels. The type < – channel int represents a channel that only receives int, and the channel < – int represents a channel that only sends int. (the relative position of the arrow < – and the keyword channel indicates the direction of the channel. ), which will be detected at compile time.


func counter(out chan<- int) {
	for x := 0; x < 100; x++ {
			out <- x
		}
		close(out)
	}
	func squarer(out chan<- int, in <-chan int) {
		for v := range in {
			out <- v * v
		}
		close(out)
	}
	func printer(in <-chan int) {
		for v := range in {
			fmt.Println(v)
		}
	}
	func main() {
		naturals := make(chan int)
		squares := make(chan int)
		go counter(naturals)
		go squarer(squares, naturals)
		printer(squares)
}

7 channels with cache

The cached channel holds an element queue internally. The maximum capacity of the queue is specified by the second parameter when the make function is called to create the channel.
The sending operation to the cache channel is to insert elements into the tail of the internal cache queue, while the receiving operation is to delete elements from the head of the queue. If the internal cache queue is full, the send operation will block until the new queue space is released by another goroutine performing a receive operation. Conversely, if the channel is empty, the receive operation will block until another goroutine performs the send operation and inserts an element into the queue.

  • Write: the write side will not block until the buffer is filled.
  • Read: the read end will block only when the buffer is read empty.

The built-in cap function can be used to obtain the internal cache capacity of channel


fmt.Println(cap(ch)) // "3"

You can use the built-in len function to get the number of effective elements in the channel internal cache queue.


fmt.Println(len(ch)) // "2"

Here is the article about the usage of channel in golang. For more information about the usage of channel in golang, please search previous articles of developer or continue to browse the following articles. I hope you can support developer more in the future!

Recommended Today

Use of Android WebView (super detailed usage)

1.1 overview of WebView Android WebView is a special view on the Android platform. It can be used to display web pages. This WebView class can be used to display only one online web page in the app. Of course, it can also be used to develop browsers. The internal implementation of WebView uses WebKit […]