Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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")
like image 337
Ali Avatar asked Sep 04 '13 21:09

Ali


2 Answers

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.

like image 136
Wessie Avatar answered Sep 22 '22 13:09

Wessie


If you want to run each loop in the background, nest the goroutine in the loop and use the sync.WaitGroup structure.

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")
like image 35
Byron Ruth Avatar answered Sep 20 '22 13:09

Byron Ruth