创建一个协程

golang创建协程的关键字是go

  • go xxxx()
  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. func task(id int) {
  7. for {
  8. fmt.Println("child task:",id)
  9. time.Sleep(1*time.Second)
  10. }
  11. }
  12. func main() {
  13. go task(1)
  14. go task(2)
  15. go task(3)
  16. for {
  17. }
  18. }
  1. child task: 1
  2. child task: 2
  3. child task: 3
  4. child task: 3
  5. child task: 1
  6. child task: 2