当前位置:网站首页>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
边栏推荐
- 基于昇腾AI丨爱笔智能推出银行网点数字化解决方案,实现从总部到网点的信息数字化全覆盖
- Based on shengteng AI Aibi intelligence, we launched a digital solution for bank outlets to achieve full digital coverage of information from headquarters to outlets
- 32:第三章:开发通行证服务:15:浏览器存储介质,简介;(cookie,Session Storage,Local Storage)
- Advanced scaffold development
- DOM//
- How to introduce devsecops into enterprises?
- 跨页面通讯
- A usage example that can be compatible with various database transactions
- 关于vray5.2怎么关闭日志窗口
- DGL中的消息传递相关内容的讲解
猜你喜欢

不要再说微服务可以解决一切问题了!

In the last process before the use of the risk control model, 80% of children's shoes are trampled here

2022 mobile crane driver examination question bank and simulation examination

The first product of Sepp power battery was officially launched

Intelligent metal detector based on openharmony

Codeforces Round #804 (Div. 2)

32: Chapter 3: development of pass service: 15: Browser storage media, introduction; (cookie,Session Storage,Local Storage)

【DNS】“Can‘t resolve host“ as non-root user, but works fine as root

Explanation of message passing in DGL
![[advertising system] parameter server distributed training](/img/8b/558c2fefbd16b580546003f3afeaf5.png)
[advertising system] parameter server distributed training
随机推荐
Basic part - basic project analysis
Repair animation 1K to 8K
Sqlserver regularly backup database and regularly kill database deadlock solution
关于 “原型” 的那些事你真的理解了吗?【上篇】
9、 Disk management
Nuxt//
go语言学习笔记-初识Go语言
The first product of Sepp power battery was officially launched
Basic testing process of CSDN Software Testing Introduction
Taro advanced
[advertising system] incremental training & feature access / feature elimination
Web3 Foundation grant program empowers developers to review four successful projects
When using gbase 8C database, an error is reported: 80000502, cluster:%s is busy. What's going on?
【广告系统】Parameter Server分布式训练
NAS and San
[advertising system] parameter server distributed training
关于vray 5.2的使用(自研笔记)
Go-3-the first go program
力扣(LeetCode)185. 部门工资前三高的所有员工(2022.07.04)
How can gbase 8C database view the login information of the login user, such as the date, time and IP of the last login authentication?