Newer
Older
01_hello / goroutine / parallel.go
yhornisse on 9 Oct 2021 459 bytes add sample
package main

import (
	"fmt"
)

func main() {
	ng() // 2, 2, 2
	ok() // 0, 1, 2
}

func ng() {
	ary := [3]int{1, 2, 3}
	done := make(chan bool)
	for i := range ary {
		go func() {
			fmt.Println(i) // NG
			done <- true
		}()
	}
	for i := 0; i < 3; i++ {
		<- done
	}
}

func ok() {
	ary := [3]int{1, 2, 3}
	done := make(chan bool)
	for i := range ary {
		go func(i int) {
			fmt.Println(i)
			done <- true
		}(i)
	}
	for i := 0; i < 3; i++ {
		<- done
	}
}