当前位置:网站首页>go channel && select
go channel && select
2022-06-30 14:09:00 【Zhen Jie.】
channel brief introduction
goroutine yes Go An important mechanism for implementing concurrency in ,channel yes goroutine An important bridge for communication between .channel It's a kind of go A secure message queue used by a process to receive or send messages ,channel It's like two go The catheter between the processes , To synchronize resources .
Reputation creation channel There are two common ways ,
// The way 1: Use make establish ( The data type it passes must be defined )
ch :make(chan int, 2) // Create buffer channels
ch :make(chan int) // Create unbuffered channels
ch :make(chan string, 0) // Create unbuffered channels
// The way 2: Use it directly var Statement
var ch chan int
buffer channel And unbuffering channel
buffer channel: Have buffer , When the buffer is full , The sender will jam ; When the buffer is empty , The recipient will jam .
Simple use example , as follows
func main() {
ch := make(chan int, 1) // Create a type of int, The buffer size is 1 Of channel
ch <- 2 // take 2 Send to ch
n, ok := <- ch // n Receive from ch The value of the emission
if ok {
fmt.Println(n) // Output :2
}
close(ch) // close channel
}
Use channel Points for attention :
- To an already close fall Of channel Send a message , Will trigger panic;
- It is not allowed to report to the closed channel Send a message , But you can continue channel receive messages ;
- To one nil Of channel Send a message , It's going to keep clogging up ;
- When channel closed And channel The cache is empty when , Continue from channel Receiving a message will get a zero value of the corresponding type .
Non buffering channel: The buffer size is 0 Of channel, such channel The recipient of will block until the message is received , The sender will block until the receiver receives the message , This mechanism can be used for two goroutine State synchronization .
A simple example :main In the function goroutine, Through the use of unbuffered queues , To be able to guarantee that goroutine Before the end of execution main The function does not exit prematurely , as follows :
func worker(done chan bool){
fmt.Println("start working...")
done <- true
fmt.Println("end working...")
}
func main() {
done := make(chan bool, 1)
go worker(done)
<- done
}
select brief introduction
select Dedicated to channel send and receive operations , Looks like switch Very similar , But the methods of choice and judgment are completely different .
In the following example , adopt select Use , To ensure the worker The transaction in can be executed before exiting main function
func strWorker(ch chan string) {
time.Sleep(1 * time.Second)
fmt.Println("do something with strWorker...")
ch <- "str"
}
func intWorker(ch chan int) {
time.Sleep(2 * time.Second)
fmt.Println("do something with intWorker...")
ch <- 1
}
func main() {
chStr := make(chan string)
chInt := make(chan int)
go strWorker(chStr)
go intWorker(chInt)
for i := 0; i < 2; i++ {
select {
case <-chStr:
fmt.Println("get value from strWorker")
case <-chInt:
fmt.Println("get value from intWorker")
}
}
}
边栏推荐
- Rpm2rpm packaging steps
- 想请教一下,我在佛山,到哪里开户比较好?手机开户是安全么?
- visualstudio 和sql
- DeFi“钱从哪来”?一个大多数人都没搞清楚的问题
- Exlipse operates on multiple rows at the same time. For example, input the same text in multiple lines and columns at the same time
- Mysql database foundation: stored procedures and functions
- 我如何才能保护我的私钥?
- 嵌入式开发:5个可能不再被禁止的C特征
- Google Earth Engine(GEE)——将字符串的转化为数字并且应用于时间搜索( ee.Date.fromYMD)
- Unity 频繁切换分支 结果模型出现莫名其妙的错误
猜你喜欢

正则系列之断言Assertions

About the problems encountered when using the timer class to stop with a button (why does the QPushButton (for the first time) need to be clicked twice to respond?)

Google Earth Engine(GEE)——GHSL:全球人类住区层,建成网格 1975-1990-2000-2015 (P2016) 数据集

香港回归20余年,图扑数字孪生港珠澳大桥,超震撼
![[kali] Kali system, software update (with image source)](/img/ac/43a3f81d50ab6866271b500b142252.png)
[kali] Kali system, software update (with image source)

Multi terminal collaboration of Huawei accounts to create a better internet life
![[scientific research data processing] [basic] category variable frequency analysis chart, numerical variable distribution chart and normality test (including lognormal)](/img/70/8bf226964118efb324ca4d339df654.png)
[scientific research data processing] [basic] category variable frequency analysis chart, numerical variable distribution chart and normality test (including lognormal)

重磅:国产IDE发布,由阿里研发,完全开源!

MFQE 2.0: A New Approach for Multi-FrameQuality Enhancement on Compressed Video

Observable, reliable: the first shot of cloudops series Salon of cloud automation operation and maintenance
随机推荐
SQL考勤统计月报表
Configuration of headquarters dual computer hot standby and branch infrastructure for firewall Foundation
DNS resolution home network access public DNS practice
【Redis 系列】redis 学习十六,redis 字典(map) 及其核心编码结构
第四批入围企业公示——年度TOP100智能网联供应商评选
Unity 频繁切换分支 结果模型出现莫名其妙的错误
【系统分析师之路】第五章 复盘软件工程(软件过程改进)
There is no utf8 option for creating tables in Navicat database.
Jetpack Compose 实现完美屏幕适配
Numpy creates an empty array data = np empty(shape=[1, 64,64,3])
Apache Doris Compaction優化百科全書
Golang template (text/template)
【系统分析师之路】第五章 复盘软件工程(敏捷开发)
重磅:国产IDE发布,由阿里研发,完全开源!
This editor will open source soon!
Heavyweight: the domestic ide was released, developed by Alibaba, and is completely open source!
提权扫描工具
嵌入式开发:5个可能不再被禁止的C特征
Impersonate server and client using message queuing
[Title brushing] heater