当前位置:网站首页>《Go题库·11》channel的应用场景
《Go题库·11》channel的应用场景
2022-06-24 18:34:00 【GolangRoadmap】
*「题目解析」GOLANG ROADMAP社区
*
「答案」(engine)
channel适用于数据在多个协程中流动的场景,有很多实际应用:
① 任务定时
比如超时处理:
select {
case <-time.After(time.Second):
定时任务
select {
case <- time.Tick(time.Second)
② 解耦生产者和消费者
可以将生产者和消费者解耦出来,生产者只需要往channel发送数据,而消费者只管从channel中获取数据。
③ 控制并发数
以爬虫为例,比如需要爬取1w条数据,需要并发爬取以提高效率,但并发量又不能过大,可以通过channel来控制并发规模,比如同时支持5个并发任务:
ch := make(chan int, 5)
for _, url := range urls {
go func() {
ch <- 1
worker(url)
<- ch
}
}
边栏推荐
- 干货 | 新手经常忽略的嵌入式基础知识点,你都掌握了吗?
- JS position operation
- 2022 network security C module of the secondary vocational group scans the script of the surviving target aircraft (municipal, provincial and national)
- congratulate! The first dragon lizard community annual outstanding contribution award is announced. Check it now
- Building MVC system based on three-tier structure
- JS clothing photo album case
- Leetcode weekly buckle 281
- 360 digital released information security trends in January: 120000 fraud risks were captured and users were reminded 2.68 million times
- LabView之MQTT协议使用
- NOKOV动作捕捉系统使多场协同无人机自主建造成为可能
猜你喜欢
随机推荐
Interview algorithm - string question summary
subject may not be empty [subject-empty]
JS picture display and hiding cases
Industry Cloud video editing software
What are the grades of financial products?
Flex box flex attribute
如何在 R 中使用 Fisher 的最小显着性差异 (LSD)
微服務系統設計——子服務項目構建
Is there a security risk in opening an account online? What to do if the business department opening an account nearby is far away from home. Is there any capital requirement for opening an account?
微服务系统设计——数据模型与系统架构设计
1: Mosaic of 100W basic geographic information data
three.js创建的基础框架
微服务系统设计——接口文档管理设计
BOM(Browser Object Model)
How to perform robust regression in R
上位机与MES对接的几种方式
variable
电源噪声分析
如何在 R 中执行稳健回归
Leetcode weekly buckle 281