go语言-goroutine

luckyFang 2021年03月15日 96次浏览

创建一个协程

golang创建协程的关键字是go

  • go xxxx()
package main

import (
	"fmt"
	"time"
)

func task(id int)  {
	for  {
		fmt.Println("child task:",id)
		time.Sleep(1*time.Second)
	}
}



func main() {
	go task(1)
	go task(2)
	go task(3)

	for  {

	}
}

child task: 1
child task: 2
child task: 3
child task: 3
child task: 1
child task: 2