当前位置:网站首页>GO语言-goroutine协程的使用
GO语言-goroutine协程的使用
2022-06-24 13:03:00 【一边学习一边哭】
前言
协程的英文coroutine,go语言中的协程为goroutine。Go是并发语言,而不是并行语言。
go语言的协程创建十分简单,只需要在调用的函数前面加上go关键字,程序就会同事运行一个新的goroutine。
但是goroutine中没有返回值,会忽略返回值。所以往往需要通过channel进行goroutine之间的通信。
goroutine使用
func main() {
go mytest()
for i := 0; i < 100; i++ {
fmt.Println("主函数输出:", i)
}
}
func mytest() {
for i := 0; i < 500; i++ {
fmt.Println("goroutine中输出数字:", i)
}
}
通过这个简单的示例输出,可以总结goroutine的两个特点:
- goroutine协程中的函数执行和主函数的执行是同时的,输出内容是交替的。
- 主程序结束后,即使子goroutine没有执行完成,也会随主程序一同结束。
sync包-WaitGroup
一般情况下,主程序结束后,子goroutine就会结束。
为了让主程序等待子groutine执行完成,一种方法是使用sleep。但是sleep存在一个问题是,我们没办法知道子goroutine需要执行的具体时长,只能尽量放长sleep的时间。
所以我们可以使用到sync包的WaitGroup解决主进程等待子goroutine的问题。
var wg sync.WaitGroup
func main() {
wg.Add(1) //定义WaitGroup队列长度,长度为1
go mytest()
for i := 0; i < 100; i++ {
fmt.Println("主函数输出:", i)
}
wg.Wait() //主程序最后,等待WaitGroup队列为0时再退出
}
func mytest() {
for i := 0; i < 500; i++ {
fmt.Println("goroutine中输出数字:", i)
}
wg.Done() //相当于wg.Add(-1),一个goroutine结束,调用wg.Done(),队列减一
}
wg.Add(1) 主函数中,定义WaitGroup队列长度
wg.Done() 子goroutine中,函数最后调用,相当于将WaitGroup队列长度-1
wg.Wait() 主函数中,在主函数的最后,等待WaitGroup队列长度为0
边栏推荐
- A review of text contrastive learning
- 鲲鹏arm服务器编译安装PaddlePaddle
- 远程办公之:在家露营办公小工具| 社区征文
- Antd checkbox, limit the selected quantity
- English writing of Mathematics -- Basic Chinese and English vocabulary (common vocabulary of geometry and trigonometry)
- 百度地图API绘制点及提示信息
- Three efficient programming skills of go language
- Unity 热力图建立方法
- Return to new list
- Harmony os. (2)
猜你喜欢

Method of inputting dots under letters in markdown/latex

laravel下视图间共享数据

IDEA连接mysql自定义生成实体类代码

Three efficient programming skills of go language

HarmonyOS-3

Idea connection MySQL custom generated entity class code

Solution of channel management system for food and beverage industry: realize channel digital marketing layout

打败 二叉树!

unity 等高线创建方法

Télétravail: Camping à la maison gadgets de bureau | rédaction communautaire
随机推荐
OpenHarmony 1
The function and principle of key in V-for
win10系统问题
[learn ZABBIX from scratch] I. Introduction and deployment of ZABBIX
Jericho may have some chips with fast music playing speed [chapter]
专精特新“小巨人”再启动,“企业上云”数字赋能
10_ Those high-profile personal signatures
二造考生必看|巩固优选题库助力考生最后冲刺
conda和pip命令
Return to new list
AQS初探
Go语言三个高效编程的技巧
The project manager needs to look at six characteristics to build a team
厨卫电器行业B2B交易协同管理平台开发,优化企业库存结构
数字臧品系统开发 NFT数字臧品系统异常处理源码分享
【Pytorch】量化
Télétravail: Camping à la maison gadgets de bureau | rédaction communautaire
Rongyun communication has "hacked" into the heart of the bank
c语言---18 函数(自定义函数)
Linux 安装 CenOS7 MySQL - 8.0.26