请教 Golang 的 goroutine 用法
本文介绍了请教 Golang 的 goroutine 用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
这段代码执行为何没有输出?
package main
import (
"fmt"
)
func test() {
for i := 0; i < 9; i++ {
fmt.Println("hello")
}
}
func main() {
go test()
}
总结了一下 goroutine 的基本用法
https://blog.tanteng.me/2017/...
解决方案
goroutine未来得及执行,主进程就退出了。
可以用channel来同步
func test(done chan bool) {
for i := 0; i < 9; i++ {
fmt.Println("hello")
}
done <- true
}
func main() {
done := make(chan bool)
go test(done)
<- done
}
这篇关于请教 Golang 的 goroutine 用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文