Skip to content

Goroutine 与 Channel

Goroutine

go
go func() {
    fmt.Println("并发执行")
}()

Channel

go
ch := make(chan string)

// 发送
go func() { ch <- "hello" }()

// 接收
msg := <-ch
fmt.Println(msg)

select

go
select {
case msg := <-ch1:
    fmt.Println("ch1:", msg)
case msg := <-ch2:
    fmt.Println("ch2:", msg)
case <-time.After(5 * time.Second):
    fmt.Println("超时")
}

sync.WaitGroup

go
var wg sync.WaitGroup

for i := 0; i < 3; i++ {
    wg.Add(1)
    go func(id int) {
        defer wg.Done()
        fmt.Printf("Worker %d\n", id)
    }(i)
}
wg.Wait()

基于 VitePress 构建