0097-Go-协程

环境

  • Time 2022-08-24
  • Go 1.19

前言

说明

参考:https://gobyexample.com/goroutines

目标

使用 Go 语言的协程。

启动函数协程

package main

import (
    "fmt"
    "time"
)

func f(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
    }
}

func main() {

    f("direct")
    go f("goroutine")
    time.Sleep(time.Second)
    fmt.Println("done")
}

启动匿名函数协程

package main

import (
    "fmt"
    "time"
)

func f(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
    }
}

func main() {

    f("direct")

    go f("goroutine")

    go func(msg string) {
        fmt.Println(msg)
    }("going")

    time.Sleep(time.Second)
    fmt.Println("done")
}

总结

使用 Go 语言的协程。

附录

posted @ 2022-10-30 08:31  jiangbo4444  阅读(36)  评论(0)    收藏  举报