主协程和子协程的并发执行-闭包的使用
2018-12-10 本文已影响0人
bocsoft
package main
import (
"fmt"
"time"
)
func main() {
names := []string{"Eric", "Harry", "Robert", "Jim", "Mark"}
for _, name := range names {
go func(who string) {
fmt.Printf("Hello,%s!\n", who)
}(name)
}
//如果此行注释掉,主协程结束且子协程无任何打印输出
time.Sleep(time.Millisecond)
}
/*
输出结果为:
Hello,Eric!
Hello,Jim!
Hello,Mark!
Hello,Harry!
Hello,Robert!
*/