当前位置:网站首页>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 .
边栏推荐
猜你喜欢

What features are added to Photoshop 2022 23.4.1? Do you know anything

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

李航老师新作《机器学习方法》上市了!附购买链接

防火墙介绍

NVM installation tutorial

Stack, LIFO

Design of four kinds of linear phase FIR filters -- complete set of Matlab source code

There are many contents in the widget, so it is a good scheme to support scrolling
![[how to connect the network] Chapter 2 (next): receiving a network packet](/img/f5/33e1fd8636fcc80430b3860d069866.png)
[how to connect the network] Chapter 2 (next): receiving a network packet

Adapter mode
随机推荐
Nlp-d60-nlp competition D29
MediaPipe手势(Hands)
Solutions to insufficient display permissions of find and Du -sh
Uva11582 [fast power]colossal Fibonacci numbers!
Electron official docs series: Testing And Debugging
tauri vs electron
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
Mediapipe gestures (hands)
MariaDB study notes
Beifu realizes the control of time slice size and quantity through CTU and ton
李航老师新作《机器学习方法》上市了!附购买链接
Guruiwat rushed to the Hong Kong stock exchange for listing: set "multiple firsts" and obtained an investment of 900million yuan from IDG capital
Beifu PLC based on NT_ Shutdown to realize automatic shutdown and restart of controller
May product upgrade observation station
Script - crawl the customized storage path of the cartoon and download it to the local
MongoDB系列之适用场景和不适用场景
First pass! Baidu AI Cloud Xiling platform has obtained the authoritative certification of digital human ability evaluation from the Institute of information technology
Beifu PLC obtains system time, local time, current time zone and system time zone conversion through program
I - Dollar Dayz
Bridge mode