当前位置:网站首页>Go language - pipeline channel
Go language - pipeline channel
2022-06-26 13:30:00 【Crying while learning】
summary
passageway channel Can be thought of as goroutine Communication pipeline . About the previous article go The language lock blog also mentioned , Lock can be used to solve the critical resource problem , But it is more recommended to use channel To achieve goroutine Communication between .
Don't communicate through shared memory , Instead, share memory through communication .
- It's important to note that ,channel It's synchronous in itself . It means there is only one at a time goroutine To operate channel.
- Deadlock —— If one channel Only read data , Without writing data , A deadlock occurs . vice versa . If you accidentally create a deadlock when writing code ,go The language will throw related exceptions .
channel Creation and use of channels
channel Statement
Each channel has its associated type , This type is the data type allowed to be transmitted in the channel .
Empty channel is nil,nil There is no use in the passage of . So the declaration of the channel is and map Allied .
// Declaration channel
var channel_name chan type
// Initialize channel
channel_name = make(chan type)A short statement
channel_name := make(chan type)channel Read and write operations
data := <- channel_name // Assign the value in the channel to the variable
channel_name <- data // Write the value of the variable to the channel
value, ok := <- channel_name // From a channel Read value in channel All read and write operations are blocked
Under normal circumstances , If not used sync.WaitGroup Sync wait group 、 lock , Children in the main function goroutine It is likely that when it has not been implemented , Because of the end of the main function .
But it can go through “channel All read and write operations are blocked ”, Son goroutine adopt channel The channel passes information to the master goroutine, Lord goroutine It will block until the data is read .
func main() {
channel1 := make(chan bool)
go func(){
for i:=0;i<10;i++{
fmt.Println(i)
}
channel1 <- true
fmt.Println(" Son goroutine end ...")
}()
data1 := <- channel1
fmt.Println("channel Value delivered :",data1)
fmt.Println(" End of main function ...")
}close channel passageway
The sender can turn off channel passageway , Inform the receiver that no more data will be sent to channel Yes .
close(channel_name)The recipient can accept from channel When reading data , Use additional variables to check whether the channel is closed .
ok by true when , Indicates that a... Is read from the channel value; When ok yes false yes , It means that data is being read from a closed channel , Read the value Will be zero .
value, ok := <- channel_namevar channel1 = make(chan int)
func main() {
go fun1()
for{
fmt.Println(" Read the value from the channel ...")
v,ok := <-channel1
time.Sleep(1*time.Second)
if !ok {
fmt.Println("channel End of read , The passage is closed ",v,ok)
break
}
fmt.Println(" Values in the channel :",v,ok)
}
}
func fun1() {
for i:=0;i<10;i++{
time.Sleep(1*time.Second)
fmt.Println(" Write values to the channel :", i)
channel1 <- i
}
close(channel1)
}channel Range cycling of channels
adopt for_range Enhance the cycle , It is not necessary to judge whether the channel is closed .range Will judge whether the channel is closed .
var channel1 = make(chan int)
func main() {
go fun1()
for v := range channel1 { // v <- channel1
time.Sleep(1 * time.Second)
fmt.Println(v)
}
}
func fun1() {
for i := 0; i < 10; i++ {
channel1 <- i
}
close(channel1)
}Buffer channel
Buffered channel , The data will be written to the buffer first . When sending data , Only when the buffer is full will it be blocked ; When receiving data , Only when the buffer is empty will it be blocked .
ch := make(chan type, Size)Size Need greater than 0, Make the channel have a buffer . By default, the capacity of unbuffered channels is 0, So this parameter is omitted .
var channel1 = make(chan int,5) // Create a capacity 5 The buffer channel of
func main() {
go fun1()
for v := range channel1 {
time.Sleep(1 * time.Second)
fmt.Println("\t Read the data ",v)
}
}
func fun1() {
for i := 0; i < 10; i++ {
channel1 <- i
fmt.Println(" Write data :",i)
}
close(channel1)
}Directional channel
Two-way channel
The channel we created earlier , Are two-way channels . The two-way channel can , One goroutine send data , One goroutine Receiving data .
Directional channel ( One way passage )
A unidirectional channel is a directional channel . A one-way channel can only send or receive data .
Directional channel creation syntax
channel1 := make(chan <-int) // Only data can be written , Can't read data
channel2 := make(<- chan int) // Data only , Unable to write data Usage of directional channel
When creating and using channels, you usually create two-way channels . One way channels are only used as function parameter types .
Only when passing a channel as an argument to a function , The channel type in the function uses a one-way channel . The restricted channel can only be read but not written when used inside the function ; Or they can only write but not read .
边栏推荐
- Decorator
- 7-1 n queen problem
- 三维向量的夹角
- H - Sumsets POJ 2229
- MySQL讲解(二)
- 装饰器(Decorator)
- Luogu p3426 [poi2005]sza-template solution
- Wechat applet magic bug - choose to replace the token instead of clearing the token, wx Getstoragesync will take the old token value instead of the new token value
- [how to connect the network] Chapter 2 (middle): sending a network packet
- Ring queue PHP
猜你喜欢

MediaPipe手势(Hands)

Enjoy element mode (flyweight)

Ring queue PHP

C language: Exercise 2

MySQL讲解(二)

Arcpy -- use of insertlayer() function: adding layers to map documents

Script - crawl the customized storage path of the cartoon and download it to the local

Beifu PLC realizes zero point power-off hold of absolute value encoder -- use of bias

MySQL数据库讲解(三)

Beifu PLC model selection -- how to see whether the motor is a multi turn absolute value encoder or a single turn absolute value encoder
随机推荐
网络远程访问的方式使用树莓派
Uva10341 solve it
Here Document免交互及Expect自动化交互
ES基於Snapshot(快照)的數據備份和還原
HW蓝队溯源流程详细整理
C language: Exercise 2
[shell] generate strings between specified dates
[node.js] MySQL module
MySQL explanation (I)
创建一个自己的跨域代理服务器
防火墙介绍
MariaDB study notes
MongoDB系列之适用场景和不适用场景
遍历指定目录获取当前目录下指定后缀(如txt和ini)的文件名
Gurivat sprint Harbour Exchange listed: created “multiple first”, received 900 million yuan Investment from IDG capital
偶言佳句,孤芳自赏
LAMP编译安装
IDC report: the AI cloud market share of Baidu AI Cloud ranks first for six consecutive times
Here document interaction free and expect automatic interaction
A few lines of code can realize complex excel import and export. This tool class is really powerful!