«

如何在不阻塞的情况下判断 Goroutine 是否完成?

磁力搜索 • 15 小时前 • 0 次点击 • 资讯分享


如何在不阻塞的情况下判断 goroutine 是否完成?

在 Go 语言中,判断一个 Goroutine 是否完成,通常需要通过 channel 进行通信。然而,直接从 channel 接收数据 (

"Comma, Ok" 模式

Go 语言的 "comma, ok" 模式允许在从 channel 接收数据时,同时获取一个布尔值,指示 channel 是否已关闭。如果 channel 已经关闭,该布尔值为 false;否则,为 true。

以下是一个示例:

package main

import (
    "fmt"
    "time"
)

func worker(ch chan int) {
    defer close(ch) // Goroutine 完成后关闭 channel
    time.Sleep(2 * time.Second)
    ch <- 123 // 向 channel 发送数据
}

func main() {
    ch := make(chan int)
    go worker(ch)

    // 非阻塞地检查 Goroutine 是否完成
    for {
        select {
        case val, ok := <-ch:
            if ok {
                fmt.Println("Received:", val)
                fmt.Println("Goroutine is still running.")
            } else {
                fmt.Println("Channel is closed.")
                fmt.Println("Goroutine has finished.")
                return
            }
        default:
            fmt.Println("No data available yet, checking again...")
            time.Sleep(500 * time.Millisecond) // 避免 CPU 占用过高
        }
    }
}
登录后复制


    还没收到回复