package main import ( "fmt" ) func main() { for i := 0; i < 10; i++{ go func() { fmt.Println(i) }() } }
输出为空-->主goroutine执行完毕,程序就结束运行,不会等待go函数执行完毕
package main import ( "fmt" "time" ) func main() { for i := 0; i < 10; i++{ go func(i int) { fmt.Println(i) }(i) time.Sleep(time.Second) } }
package main import ( "fmt" "sync/atomic" "time" ) func main() { var count uint32 trigger := func(i uint32, fn func()) { for { if n := atomic.LoadUint32(&count); n == i { fn() atomic.AddUint32(&count, 1) break } time.Sleep(time.Nanosecond) } } for i := uint32(0); i < 10; i++{ go func(i uint32) { fn := func() { //传参可以保证每个goroutine拿到唯一的一个整数 fmt.Println(i) } trigger(i, fn) }(i) time.Sleep(time.Second) } trigger(10, func() {}) }