当前位置:网站首页>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
边栏推荐
- Deepfake tutorial
- 第五届 Polkadot Hackathon 创业大赛全程回顾,获胜项目揭秘!
- Use bat command to launch common browsers with one click
- 【广告系统】增量训练 & 特征准入/特征淘汰
- websocket
- DDR4的特性与电气参数
- Crawler (9) - scrape framework (1) | scrape asynchronous web crawler framework
- Pull up loading principle
- Bidirectional RNN and stacked bidirectional RNN
- Beego cross domain problem solution - successful trial
猜你喜欢

2022 mobile crane driver examination question bank and simulation examination

Do you really understand the things about "prototype"? [part I]

【广告系统】增量训练 & 特征准入/特征淘汰

DGL中异构图的一些理解以及异构图卷积HeteroGraphConv的用法

DDR4的特性与电气参数

购买小间距LED显示屏的三个建议

Characteristics and electrical parameters of DDR4

赛克瑞浦动力电池首台产品正式下线

Implement the rising edge in C #, and simulate the PLC environment to verify the difference between if statement using the rising edge and not using the rising edge

在C# 中实现上升沿,并模仿PLC环境验证 If 语句使用上升沿和不使用上升沿的不同
随机推荐
Some understandings of heterogeneous graphs in DGL and the usage of heterogeneous graph convolution heterographconv
Taro进阶
Bracket matching problem (STL)
How to make full-color LED display more energy-saving and environmental protection
websocket
上拉加载原理
图片懒加载的方案
埋点111
Operators
使用bat命令一键启动常用浏览器
matlab cov函数详解
力扣(LeetCode)185. 部门工资前三高的所有员工(2022.07.04)
Honing · fusion | know that the official website of Chuangyu mobile terminal is newly launched, and start the journey of digital security!
九、磁盘管理
跨页面通讯
[JS] extract the scores in the string, calculate the average score after summarizing, compare with each score, and output
Go project practice - Gorm format time field
Common functions of go-2-vim IDE
2021年山东省赛题库题目抓包
Lazy loading scheme of pictures