Home > Backend Development > Golang > What is chan channel in Go language

What is chan channel in Go language

青灯夜游
Release: 2023-01-11 18:03:10
Original
1985 people have browsed it

In the Go language, channel (chan) is a communication pipe between goroutines and a medium for goroutine to communicate with another goroutine. Channels are a technology that allows one goroutine to send data to another goroutine; by default, channels are bidirectional, meaning a goroutine can send or receive data through the same channel.

What is chan channel in Go language

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

In the Go language, a channel (chan) is a pipeline for communication between goroutines. It is a medium for goroutine to communicate with another goroutine, and this communication is lock-free. In other words, a channel is a technology that allows one goroutine to send data to another goroutine. By default, the channel is bidirectional, which means that goroutine can send or receive data through the same channel, as shown in the following figure:

What is chan channel in Go language

Go language advocates using communication methods instead Shared memory, when a resource needs to be shared between goroutines, the channel sets up a pipeline between goroutines and provides a mechanism to ensure synchronous exchange of data. When declaring a channel, you need to specify the type of data that will be shared. Values ​​or pointers of built-in types, named types, structure types, and reference types can be shared through channels.

The method of communication here is to use channels, as shown in the figure below.

What is chan channel in Go language
Picture: Communication between goroutine and channel

In situations where there are many people in public places such as subway stations, canteens, and restrooms, everyone has developed the habit of queuing. It also avoids inefficient resource use and exchange processes caused by crowding and queue jumping. The same is true for code and data. In order to compete for data, multiple goroutines will inevitably cause inefficiency in execution. The most efficient way is to use a queue. Channel is a queue-like structure.

Characteristics of channels

Channel (channel) in Go language is a special type. At any time, only one goroutine can access the channel to send and obtain data. Goroutines can communicate through channels.

The channel is like a conveyor belt or queue, always following the first in first out (First In First Out) rule to ensure the order of sending and receiving data.

Create channel

In Go language, use the chan keyword to create a channel, and the channel can only transmit the same type of data, not Allows different types of data to be transferred from the same channel.

Syntax:

var Channel_name chan Type
Copy after login

You can also create a channel through the make() function using a shorthand declaration.

Syntax:

channel_name:= make(chan Type)
Copy after login

Example

package main
import "fmt"
func main() {
    //使用var关键字创建通道
    var mychannel chan int
    fmt.Println("channel的值: ", mychannel)
    fmt.Printf("channel的类型: %T ", mychannel)
    // 使用 make() 函数创建通道
    mychannel1 := make(chan int)
    fmt.Println("\nchannel1的值:", mychannel1)
    fmt.Printf("channel1的类型: %T ", mychannel1)
}
Copy after login

Output:

channel的值:  <nil>
channel的类型: chan int
channel1的值: 0xc0000160c0
channel1的类型: chan int
Copy after login

Sending and receiving data from the channel

In the Go language, channel work has two main operations, one is sending and the other is receiving. These two operations are collectively called communication. <-The direction of the operator indicates whether to receive data or send data. In a channel, by default, send and receive operations block until there is no data at the other end. It allows goroutines to synchronize with each other without explicit locks or condition variables.

1. Send operation: The send operation is used to send data from one goroutine to another goroutine with the help of channels. Values ​​like int, float64, and bool can be safely and easily sent over a channel because they are copied, so there is no risk of accidental concurrent access to the same value. Likewise, strings are safe because they are immutable. However, sending pointers or references (such as slices, map collections, etc.) through channels is not safe because the value of the pointer or reference may change by sending or receiving goroutines at the same time, and the results are unpredictable. Therefore, when using pointers or references in channels, you must ensure that they can only be accessed by one goroutine at a time.

Mychannel <- element
Copy after login

The above statement indicates that data (element) is sent to the channel (Mychannel) with the help of <- operator.

2. Receiving operation: The receiving operation is used to receive the data sent by the sending operator.

element := <-Mychannel
Copy after login

The above statement indicates that the element receives data from the channel (Mychannel). This is also a valid statement if the result of the received statement is not available (does not need to be used). You can also write the following receive statement:

<-Mychannel
Copy after login

Example

package main 
 
import "fmt"
  
func myfunc(ch chan int) { 
  
    fmt.Println(234 + <-ch) 
} 
func main() { 
    fmt.Println("主方法开始") 
    //创建通道l 
    ch := make(chan int) 
  
    go myfunc(ch) 
    ch <- 23 
    fmt.Println("主方法结束") 
}
Copy after login

Output:

主方法开始
257
主方法结束
Copy after login

[Related recommendations: Go video tutorial, Programming teaching

The above is the detailed content of What is chan channel in Go language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template