英文:
Is there a way to run a for loop as a go routine without putting it in a separate func
问题
假设我想要设置一个运行的for循环,但不想阻塞执行,显然我可以将for循环放在一个函数f
中,并调用go f
,然后继续我的生活,但我很好奇是否有一种直接调用go for
的方法,类似于:
fmt.Println("我们正在做某事")
//下面这行是我的问题
go for i := 1; i < 10; i++ {
fmt.Println("后台运行的任务")
}
//生活继续
fmt.Println("这就是生活")
英文:
Let's say I want to set a for loop running but don't want to block the execution, obviously I can put the for loop in a function f
and call go f
and continue with my life,
but I was curious if there is a way to call go for
directly, something like:
fmt.Println("We are doing something")
//line below is my question
go for i := 1; i < 10; i ++ {
fmt.Println("stuff running in background")
}
// life goes on
fmt.Println("c'est la vie")
答案1
得分: 13
唯一的方法是通过创建一个围绕它的函数来实现。在你的例子中,你可以这样做:
fmt.Println("我们正在做一些事情")
//下面这行是我的问题
go func() {
for i := 1; i < 10; i++ {
fmt.Println("后台运行的任务")
}
}()
//生活继续
fmt.Println("这就是生活")
请注意,在最后调用函数时使用了 }()
。否则,编译器会向你报错。
英文:
The only way to do this is indeed by creating a function around it. In your example this is how you would do it.
fmt.Println("We are doing something")
//line below is my question
go func() {
for i := 1; i < 10; i ++ {
fmt.Println("stuff running in background")
}
}()
// life goes on
fmt.Println("c'est la vie")
Make note of the actual calling of the function at the end }()
. As otherwise the compiler will complain to you.
答案2
得分: 11
如果你想要在后台运行每个循环,请将goroutine嵌套在循环中,并使用sync.WaitGroup
结构。
import "sync"
fmt.Println("我们正在做一些事情")
// 下面这行是我的问题
wg := sync.WaitGroup{}
// 确保所有的协程在返回之前都完成
defer wg.Wait()
for i := 1; i < 10; i++ {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("后台运行的任务")
}()
}
// 生活继续
fmt.Println("这就是生活")
英文:
If you want to run each loop in the background, nest the goroutine in the loop and use the sync.WaitGroup
structure.
<!-- language: go -->
import "sync"
fmt.Println("We are doing something")
//line below is my question
wg := sync.WaitGroup{}
// Ensure all routines finish before returning
defer wg.Wait()
for i := 1; i < 10; i ++ {
wg.Add(1)
go func() {
defer wg.Done()
fmt.Println("stuff running in background")
}()
}
// life goes on
fmt.Println("c'est la vie")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论