[Golang] About Go language channel

What is a channel?

Since Goroutine is executed in parallel, data cannot be exchanged normally. However, you can exchange data by using channel.

It's like connecting a tunnel!


package main

import (
	"fmt"
)

func goroutine1(s []int, c chan int) {
	sum := 0
	for _, v := range s {
		sum += v
	}
    //Send data to channel
	c <- sum
}

func main() {
	s := []int{1, 2, 3, 4}
	c := make(chan int)
	go goroutine1(s, c)
      //Receive the sent data
	p := <-c
	fmt.Println(p) // => 10
}

The value is sent to c with c <-sum and received with p: = <-c. Here, it is blocked until it is received, and p is waiting until it receives sum. It's similar to sync.Wait!

Buffered channels A buffer is a memory area for temporarily storing data when processing is performed by a program. An image that stores temporary data in a channel.


package main

import "fmt"

func main() {
	//Up to 2 buffers can be saved
	ch := make(chan int, 2)
	ch <- 100
	//len()You can check the length of the channel with
	fmt.Println(len(ch))
	ch <- 200
	fmt.Println(len(ch))
	//I get an error when I try to send the third data
	ch <- 300
	fmt.Println(len(ch)) // => fatal error: all goroutines are asleep - deadlock!
}
Execution result
1
2
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan send]:
main.main()
	/tmp/sandbox795806942/prog.go:11 +0x16f

You can only save up to two, so trying to send the third will, of course, result in an error. (Deadlock)

If you take out one channel in front and send 300 as shown in ↓, no error will occur.


func main() {
	ch := make(chan int, 2)
	ch <- 100
	fmt.Println(len(ch))
	ch <- 200
	fmt.Println(len(ch))

	x := <-ch
	fmt.Println(x)
	ch <- 300
	fmt.Println(len(ch))
}
Execution result
1
2
100
2

Then look at the code below ↓


package main

import "fmt"

func main() {
	ch := make(chan int, 2)
	ch <- 100
	fmt.Println(len(ch))
	ch <- 200
	fmt.Println(len(ch))

	for c := range ch {
		fmt.Println(c)
	}
}

This is trying to loop the channel in range, but this is an error.

Execution result
1
2
100
200
fatal error: all goroutines are asleep - deadlock!

goroutine 1 [chan receive]:
main.main()
	/tmp/sandbox892357489/prog.go:12 +0x1f3

This is because it tries to loop to a third channel that doesn't exist. To stop looping on the second channel, you need to close the channel once. For that, it is necessary to describe close (ch).


package main

import "fmt"

func main() {
	ch := make(chan int, 2)
	ch <- 100
	fmt.Println(len(ch))
	ch <- 200
	fmt.Println(len(ch))
	close(ch)
	for c := range ch {
		fmt.Println(c)
	}
}
Execution result
1
2
100
200

Thank you for reading to the end!

If you have any suggestions, I would appreciate it if you could comment! !!

Recommended Posts

[Golang] About Go language channel
[Golang] About Go language Producer and Consumer
[Golang] Basics of Go language About value receiver and pointer receiver
About Go functions
[Golang] Go language basics What is Goroutine?
About Go Interface
Learn about Go slices
Go language learning record
Go language environment construction
About Go control syntax
About Go GET request
Go language cheat sheet
Features of Go language
About Go Modules (vgo)
go language learning miscellaneous notes 1
Hello World in GO language
Try implementing Yubaba in Go language
Use optinal type-like in Go language
Let's touch on the Go language
About the basic type of Go
Post to slack in Go language
Go Language Spreadsheet Library: Excelize 2.3.2 Released
2021 Go Language Framework Star Count Comparison
Write tests in GO language + gin
Do something object-oriented in GO language
Go naming rules that other language programmers should at least care about