当前位置:网站首页>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 .
边栏推荐
- Beifu PLC realizes zero point power-off hold of absolute value encoder -- use of bias
- Aesthetic experience (episode 238) Luo Guozheng
- MariaDB study notes
- B - Bridging signals
- 输入文本自动生成图像,太好玩了!
- Beifu realizes the control of time slice size and quantity through CTU and ton
- F - Charm Bracelet
- MySQL explanation (I)
- Bridge mode
- 2. Introduction to parallel interface, protocol and related chips (8080, 8060)
猜你喜欢

Lamp compilation and installation

Es6: iterator

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

mysql讲解(一)

Fire warning is completed within 10 seconds, and Baidu AI Cloud helps Kunming Guandu build a new benchmark of smart city

Bridge mode

Beifu PLC obtains system time, local time, current time zone and system time zone conversion through program

Oplg: new generation cloud native observable best practices

Beifu twincat3 can read and write CSV and txt files
![[how to connect the network] Chapter 2 (Part 1): establish a connection, transmit data, and disconnect](/img/e3/a666ba2f48e8edcc7db80503a6156d.png)
[how to connect the network] Chapter 2 (Part 1): establish a connection, transmit data, and disconnect
随机推荐
HDU 5860
MySQL explanation (II)
imagecopymerge
MySQL数据库讲解(五)
Some conclusions about Nan
橋接模式(Bridge)
原型模式(prototype)
7-2 a Fu the thief
Stack, LIFO
7-1 range of numbers
Decorator
C - Common Subsequence
Mediapipe gestures (hands)
Luogu p3426 [poi2005]sza-template solution
There are many contents in the widget, so it is a good scheme to support scrolling
Detailed practical sharing, two hours of funny videos after work, earning more than 7000 a month
I have a good word to say, and I admire myself
Electron official docs series: Processes in Electron
HW蓝队溯源流程详细整理
SQL assigns the field value of data table B to a column in data table a