当前位置:网站首页>Golang application topic - channel
Golang application topic - channel
2022-07-05 11:09:00 【Brave vegetable chicken】
channel relevant
channel Basics
1、channel The initialization
ch := make(chan int64, 10)
: Create a sendable int64 Of type data channel, Its capacity is 10
- make() Created channel It's a Reference type , When the channel When copying and function passing , It's just a copy and change channel References to
- channel have access to == Compare . When two channel When the underlying data structure is the same , return true
2、channel The closing of the
close(ch)
: Express channel Shut down
- send out . Send a message to a closed channel, Will trigger
panic
- receive .channel You can still receive after closing channel The messages in the , When channel When there is no message in , Return the zero value of the corresponding data type
- Try Close one repeatedly channel Will trigger panic abnormal
- Try Close a nil It's worth it channel Meeting panic abnormal
3、channel Data statistics of
len(ch)
: channel The number of existing elements in the queuecap(ch)
: channel The capacity of the queue
Unbuffered channel
When the initialization channel Do not specify channel capacity ( Or specify a capacity of 0) when , This channel is unbuffered channel;
1、 No buffer channel Characteristics of
An unbuffered channel The sending operation of will cause the sender to goroutine The block , Until the other goroutine In the same channel Perform receive operation on
Similarly, the receiver blocks , Until the other goroutine send out
2、 No buffer channel Use of
- Synchronous operation . Such as events A(goroutineA) Must be in the event B(goroutineB) Completed before , It's in goroutineA Medium completion time A No buffer after sending channel,goroutineB Received unified channel Message re execution event of B
- Pipeline. You can use multiple unbuffered channel Connect multiple goroutine, Form a pipe (pipeline).
3、goroutine Let the cat out of the
func testGoroutineLeak() {
ch := make(chan int64)
go func() { ch <- 64 }()
go func() { ch <- 52 }()
go func() { ch <- 41 }()
<-ch
}
When there is no buffer channel The sender of goroutine Quantity and recipients goroutine When the quantity is inconsistent , It will lead to more goroutine Blocking , And it cannot be recycled automatically (goroutine It will not be recycled automatically ), cause goroutine Let the cat out of the
Unidirectional channel
- two-way channel It can be implicitly converted to one-way channel
- On the contrary, we cannot
There is a cushion channel
When the initialization channel Specify the channel capacity , This channel is buffered channel;
Buffered channels can solve the above problems to a certain extent “ No buffer channel ” It caused goroutine Leakage problem
channel Common operation examples of
1、 Use for range read channel
scene : Need to poll channel Data in
advantage : When channel Automatically exit the cycle when closing , No additional judgment is required channel Whether to shut down ;
usage :for x := range ch {
do_something(x)
}
2、 Use _, ok Judge channel Whether to shut down
scene : read channel, But not sure channel Whether to shut down
advantage : Can pass ok Value clear judgment channel Whether to shut down , Not subject to channel Type itself 0 The impact of value
usage :if x, ok := <- chan {
do_something(x)
}
3、 Use select Processing multiple channel
scene :
- Read required / When writing multiple channels , The blocking of one channel does not affect the writing of another channel
- Need to read / Write operation increases timeout
4、 Message broadcast
scene : When the process exits , Notify all sub processes to exit . Close channel
close(ch)
after , All sub processes can sense that the channel is closed and exit automatically
channel Bottom source code implementation
channel Interview questions
In the same process , For an unbuffered channel What is the problem with sending and receiving data at the same time ? There is buffer ?
The same coroutine is serial , Can't do... At the same time “ send out ” and “ receive ” Two things , You can only send first and then receive , Or receive first and then send .
- No buffer : Can cause goroutine Blocking , The coroutine is for an unbuffered channel send out ( Or receive ) Messages will block ;
- There's a cushion : Normal execution .
- But there's no need to ? Communication of the same coroutine, direct function call or serial code logic
channel Application scenarios of ?
- Data communication between processes
- Multiple processes send and read the same channel To achieve messaging
- concurrency control
- channel Can do message diversion , Increase concurrent consumers (kafka Consumer scenario )
- Message queue
- In the local production and consumption model , Can be used as a message queue
- Synchronous operation
- Unbuffered channel It can be used as the control of synchronous operation , Events executed before need to be sent after execution channel, Events executed after receive channel And then execute
- The Conduit PIPELINE
- Multiple unbuffered channel Can connect multiple goroutine, Implement data flow pipeline ; Such as :
- goA Generate data 0、1、2 to chanA
- goB receive chanA, Perform the square operation , to chanB
- goC receive chanB, Add two numbers ; Finally, it can be realized
0 + 1*1 + 2*2 + 3*3...
This scenario
- Multiple unbuffered channel Can connect multiple goroutine, Implement data flow pipeline ; Such as :
- Message broadcast
- channel Send a specific message , The receiver receives the message and performs the agreed behavior
- Can pass close(ch) Broadcast events , Downstream receiving ch The synergy of messages is perceptible channel close , Then execute the corresponding operation
channel Comparison with lock ?
channel It's thread safe , Use channel It can solve the problem of data concurrency ; however channel The scenario to solve the concurrency problem is “ Data mobility ”, The data is moving ,channel Immobility ( It provides the ability of serial acquisition of flowing data )
lock mutex It can also solve the problem of concurrent access to resources ; however mutex More solutions “ Static data ” The problem of , That is, the data doesn't move , For a certain period of time, control only gives access to one collaboration
边栏推荐
猜你喜欢
Crawler (9) - scrape framework (1) | scrape asynchronous web crawler framework
Explanation of message passing in DGL
9、 Disk management
How to close the log window in vray5.2
How to make full-color LED display more energy-saving and environmental protection
R3live series learning (IV) r2live source code reading (2)
32: Chapter 3: development of pass service: 15: Browser storage media, introduction; (cookie,Session Storage,Local Storage)
Do you really understand the things about "prototype"? [part I]
Go language learning notes - first acquaintance with go language
Go language-1-development environment configuration
随机推荐
Applet framework taro
When using gbase 8C database, an error is reported: 80000502, cluster:%s is busy. What's going on?
Three paradigms of database
使用GBase 8c数据库过程中报错:80000502,Cluster:%s is busy,是怎么回事?
图片懒加载的方案
基础篇——基础项目解析
【全网首发】(大表小技巧)有时候 2 小时的 SQL 操作,可能只要 1 分钟
埋点111
deepfake教程
关于vray5.2怎么关闭日志窗口
赛克瑞浦动力电池首台产品正式下线
运算符、、
Beego cross domain problem solution - successful trial
Question bank and answers of special operation certificate examination for main principals of hazardous chemical business units in 2022
Three suggestions for purchasing small spacing LED display
Share Net lightweight ORM
Network security of secondary vocational group 2021 Jiangsu provincial competition 5 sets of topics environment + analysis of all necessary private messages I
Honing · fusion | know that the official website of Chuangyu mobile terminal is newly launched, and start the journey of digital security!
Data types ntext and varchar are incompatible in the not equal to operator - 95 small pang
Some understandings of heterogeneous graphs in DGL and the usage of heterogeneous graph convolution heterographconv