1

I must be missing something really basic about goroutines, but I've looked around and I cannot see any reason why this would not work...

package main

import "fmt"

func main() {
    for i := 0; i < 20; i++ {
        //fmt.Println(i)
        go func(j int) {
            fmt.Println(j + 100)
        }(i)
    }
}
Joff
  • 11,247
  • 16
  • 60
  • 103

2 Answers2

6

Your program is finishing before your goroutines have a chance to run.

Here's your code with a WaitGroup:

package main

import (
    "fmt"
    "sync"
)

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 20; i++ {
        wg.Add(1)
        go func(j int) {
            defer wg.Done()
            fmt.Println(j + 100)
        }(i)
    }
    fmt.Println("Waiting...")
    wg.Wait()
    fmt.Println("Done.")
}

https://play.golang.org/p/lmCPU9-qkB

Jack
  • 20,735
  • 11
  • 48
  • 48
1

From the spec of Go:

Program execution begins by initializing the main package and then invoking the function main. When that function invocation returns, the program exits. It does not wait for other (non-main) goroutines to complete.

See Jack's answer for a working version.

cshu
  • 5,654
  • 28
  • 44