golang并发控制代码示例

WaitGroup

package main

import (
    "fmt"
    "sync"
    "time"
)

func main() {
    var wg sync.WaitGroup

    wg.Add(2)
    go func() {
        time.Sleep(2 * time.Second)
        fmt.Println("1号完成")
        wg.Done()
    }()
    go func() {
        time.Sleep(2 * time.Second)
        fmt.Println("2号完成")
        wg.Done()
    }()
    wg.Wait()
    fmt.Println("好了,大家都干完了,放工")
}

Chan 通知

Context

Context 接口

Context的继承衍生

  • 控制一个 goroutine

  • 控制多个 goroutine

  • WithValue 传递元数据

参考链接

Last updated

Was this helpful?