当前位置:网站首页>【golang】使用select {}
【golang】使用select {}
2022-07-29 00:50:00 【JavaPub-rodert】
博主介绍: 自媒体 JavaPub 独立维护人,全网粉丝15w+,csdn博客专家、java领域优质创作者,51ctoTOP10博主,知乎/掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、
GoLang
技术领域和副业。
场景
有时我们需要让应用不退出,在后台一直运行着。
永远阻塞的作用在哪里呢? 当我们开发一个程序的时候,main函数千万不能在子协程干完活前退出,不然所有的子协程就都被迫退出了。服务也就被迫停止了。
一般会使用 channel,这里介绍下 select{}
代码
func main() {
for i := 0; i < 10; i++ {
//启动20个协程处理消息队列中的消息
c := consumer.New()
go c.Start()
}
select {
} // 阻塞
}
讲解
select 是 Go 中的一个控制结构,类似于用于通信的 switch 语句。
select 随机执行一个可运行的 case。如果没有 case 可运行,它将阻塞,直到有 case 可运行。一个默认的子句应该总是可运行的。
package main
import "fmt"
func main() {
ch1 := make(chan int, 1)
ch2 := make(chan int, 1)
ch1 <- 1
ch2 <- 1
select {
case <-ch1:
fmt.Println("ch1 pop one element")
case <-ch2:
fmt.Println("ch2 pop one element")
/* 你可以定义任意数量的 case */
default: /* 可选 */
fmt.Println("default! ")
}
}
无限循环
select{
}
边栏推荐
- T-sne dimensionality reduction
- Teach you a text to solve the problem of JS digital accuracy loss
- 活动速递| Apache Doris 性能优化实战系列直播课程初公开,诚邀您来参加!
- 新1688 API 接入说明
- body中基本标签
- Docuware mobile labor solution can help you build a new productivity model: anytime, anywhere, any device
- SQL injection of DVWA
- Three ways of creating indexes in MySQL
- 全新升级:获得淘宝商品详情“高级版” API
- JS事件简介
猜你喜欢
随机推荐
PCL point cloud intensity image
关于df[‘某一列名’][序号]
Flash reports an error: type object 'news' has no attribute' query 'the view name is duplicate with the model name
承办首届算力大会,济南胜在何处?
如何选择专业、安全、高性能的远程控制软件
Analysys analysis: focus on users, improve the user experience of mobile banking, and help the growth of user value
【HCIP】MGRE环境下OSPF实验,含多进程双向重发布及OSPF特殊区域
uniapp createSelectorQuery(). Select get returns null error
RHCE command practice (II)
Read the recent trends of okaleido tiger and tap the value and potential behind it
T-sne dimensionality reduction
Regular checksum time formatting
我们总结了 3 大Nacos使用建议,并首次公开 Nacos 3.0 规划图 Nacos 开源 4 周年
JS event introduction
Recommended Spanish translation of Beijing passport
Openpyxl library fill color
Use of resttemplate and Eureka
Merkel Studio - harmonyos implementation list to do
Docker compose install MySQL
After understanding the composition of the URL of the website, we use the URL module, querystring module and mime module to improve the static website