Goroutine是一个被Go运行时管理的轻量级线程(A goroutine is a lightweight thread managed by the Go runtime)。 为什么没有采用现有的表示并发名词来解释Go语言中的并发呢?因为现有的线程、协程、进程等都无法准确表达Goroutine。
package main
import ("fmt""time")
func ready(){
fmt.Println("Run func in a goroutine")}
func main(){
go ready()time.Sleep(time.Second*3)
fmt.Println("Main function done")}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
匿名并发函数
如果你不想单独定义,则可以使用匿名方式
package main
import ("fmt""time")
func main(){
go func(){
fmt.Println("Run anonymous func in goroutine.")}()time.Sleep(time.Second*3)
fmt.Println("Main function done")}
package main
import ("fmt"//"time")
func ready(){
fmt.Println("Run func in a goroutine")}
func main(){
go ready()//time.Sleep(time.Second*3)
fmt.Println("Main function done")}
package main
import ("fmt""time")
func ready(s int){
fmt.Printf("Run func in a goroutine and wait for %v\n", s)time.Sleep(time.Second*time.Duration(s))
fmt.Printf("Run func in a goroutine and wait for %v end\n", s)}
func main(){
mainWaitSec :=2
go ready(5)
fmt.Printf("Run Main function and wait for %v\n", mainWaitSec)time.Sleep(time.Second*time.Duration(mainWaitSec))
fmt.Printf("Run Main function and wait for %v done\n", mainWaitSec)}