How to use channel in golang development

Time:2021-4-19

Channel is an important feature of golang. It is the existence of channel that makes golang different from other languages It makes concurrent programming easy and interesting.

The concept and syntax of channel

A channel can be understood as a FIFO message queue. Channel is used to transfer data before goroutine. To be exact, it is used to transfer ownership of data. A well-designed program should ensure that the data in the channel will only be owned by the same coprocessor at the same time, so as to avoid the data races caused by concurrency.

text

Channel is mainly used for communication between multiple goroutines

Channel syntax

Channel is a reference type. You need to use make to create a channel, as follows
make(chan Type, [buffer])
The type of Chan type channel
Buffer is an optional parameter, which represents the size of the channel buffer (if omitted, it means no buffer)
Write data to channel using < – symbol


q := make(chan bool)
q<-true

The < – symbol is also used to read data from the channel, except that the written channel is on the right and the channel is on the left when reading. The meaning is consistent with the direction. One is that the data enters the channel, and the other is that the data goes out of the channel


q := make(chan bool)
<-q

The use of buffered channel

We have been using the unbuffered channel. Today we mainly study the channel with cache.
No buffer channel, write data must have goroutine read data from the channel and then write, otherwise the program will panic.


func main() {
	ch := make(chan int)
	ch<-1
}

fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:

The buffered channel can write data of buffer size, and can read from the channel without goroutine.


func main() {
	ch := make(chan int,2)
	ch<-1
	ch<-2
}


Process finished with exit code 0

The implementation result is consistent with the expectation.

Channel scenarios with buffer size

If we have a task that needs 10 goroutines to schedule, as long as one goroutine is finished, the scheduling should be finished. Let’s look at the pseudo code


func test(wg *sync.WaitGroup,ch chan int,i int) {
	fmt.Println("test code")
	ch<-i
}

func main() {
	fmt.Println("start",runtime.NumGoroutine())
	ch := make(chan int)
	wg := new(sync.WaitGroup)
	for i:=0;i<10;i++ {
		wg.Add(1)
		go test(wg,ch,i)
	}
	fmt.Println(<-ch)
	fmt.Println("end",runtime.NumGoroutine())
	wg.Done()
}

start 1
test code
9
end 10

In terms of execution results, the ninth goroutine is executed first. The program also exited normally. However, we can see that with the main goroutine, there are 11 goroutines in the memory. When the program exits, there are still 10 goroutines. Minus one main goroutine, there are still 9 goroutines that have not exited. This is not allowed for the program, which may leak or occupy resources for a long time.

But if we use the buffered channel, we can use the buffering mechanism of channel to exit all goroutines normally.
Look at the code


func test(wg *sync.WaitGroup,ch chan int,i int) {
	ch<-i
}

func main() {
	fmt.Println("start",runtime.NumGoroutine())
	ch := make(chan int, 10)
	wg := new(sync.WaitGroup)
	for i:=0;i<10;i++ {
		wg.Add(1)
		go test(wg,ch,i)
	}
	fmt.Println(<-ch,"success")
	for i:= 0;i<9;i++ {
	 fmt.Println(<-ch)
	}
	fmt.Println("end",runtime.NumGoroutine())
	wg.Done()
}

start 1
0 success
1
2
4
3
5
6
7
8
9
end 1

Process finished with exit code 0

When printing success, the first goroutine has completed the task. The loop reads out the data in the channel nine times to ensure that the created goroutine will not block and can exit normally.

This article about the use of channel in golang development is introduced here. For more information about the use of golang channel, 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

Envoy announced alpha version of native support for windows

Author: sunjay Bhatia Since 2016, porting envoy to the windows platform has been an important part of the projectOne of the goalsToday, we are excited to announce the alpha version of envoy’s windows native support. The contributor community has been working hard to bring the rich features of envoy to windows, which is another step […]