Is there a way to run a for loop as a go routine without putting it in a separate func

huangapple go评论93阅读模式
英文:

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(&quot;We are doing something&quot;)
//line below is my question
go for i := 1; i &lt; 10; i ++ {
    fmt.Println(&quot;stuff running in background&quot;)
} 
// life goes on
fmt.Println(&quot;c&#39;est la vie&quot;)

答案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(&quot;We are doing something&quot;)
//line below is my question
go func() {
    for i := 1; i &lt; 10; i ++ {
        fmt.Println(&quot;stuff running in background&quot;)
    } 
}()
// life goes on
fmt.Println(&quot;c&#39;est la vie&quot;)

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 &quot;sync&quot;

fmt.Println(&quot;We are doing something&quot;)

//line below is my question
wg := sync.WaitGroup{}

// Ensure all routines finish before returning
defer wg.Wait()

for i := 1; i &lt; 10; i ++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        fmt.Println(&quot;stuff running in background&quot;)
    }()
}

// life goes on
fmt.Println(&quot;c&#39;est la vie&quot;)

huangapple
  • 本文由 发表于 2013年9月5日 05:43:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/18624296.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定