登录
首页 >  Golang >  Go问答

如何判断一个 goroutine 成功还是所有 goroutine 都完成了?

来源:stackoverflow

时间:2024-02-20 09:33:55 296浏览 收藏

欢迎各位小伙伴来到golang学习网,相聚于此都是缘哈哈哈!今天我给大家带来《如何判断一个 goroutine 成功还是所有 goroutine 都完成了?》,这篇文章主要讲到等等知识,如果你对Golang相关的知识非常感兴趣或者正在自学,都可以关注我,我会持续更新相关文章!当然,有什么建议也欢迎在评论留言提出!一起学习!

问题内容

我正在尝试使用 dfs 通过检查图中每个节点的循环来检查图的循环。

我想为每个节点运行一个 goroutine,并在检测到第一个周期或没有周期时终止。

在检测到第一个周期时终止似乎很好,但我在将其与不再有节点时混合时遇到问题。

下面是一个似乎可以工作的实现,但对我来说看起来很糟糕,我一直在寻找更好的实现。我本质上使用缓冲通道,并在每次没有得到循环时增加计数器,并在计数器达到底层图的大小时终止。

使用计数器来确定我们何时完成对我来说似乎不习惯。或者更确切地说,如果知道 go 中是否有更惯用的方法来执行此操作,那就太好了。

func (c *cycledet) hascycle() bool {
    adj := c.b // adjacency list representation of the unerlying graph
    hascycles := make(chan bool, len(adj))

    for node := range adj {
        go func(no nodeid, co chan<- bool) {
            visited := make(map[nodeid]struct{})
            // c.nodehascycle will use a recursive implementation of dfs to
            // find out if the node no leads to a cycle.
            if c.nodehascycle(no, visited) {
                co <- true
                return
            }
            co <- false
        }(node, hascycles)
    }

    var i int
    for {
        select {
        case v := <-hascycles:
            if v {
                fmt.println("got cycle")
                return true
            }
            if i == len(c.b) {
                return false
            }
            i++
        }
    }
}

我还遇到了另一篇推荐使用“观察者”goroutine 的 so 帖子(尽管我找不到 so 帖子)。我不确定它会是什么样子,但想象它会与 waitgroups 混合,如下所示:

func (c *cycleDet) hasCycle() bool {
    hasCycle := make(chan bool)
    done := make(chan struct{})
    var wg sync.WaitGroup

    adj := c.b // adjacency list representation of the unerlying graph
    for node := range adj {
        go func(no nodeID, co chan<- bool) {
            // Use wg to synchronize termination of read-only goroutines.
            wg.Add(1)
            defer wg.Done()

            visited := make(map[nodeID]struct{})
            // c.nodeHasCycle will use a recursive implementation of DFS to
            // find out if the node no leads to a cycle.
            if c.nodeHasCycle(no, visited) {
                co <- true
                return
            }
        }(node, hasCycle)
    }

    // Observer goroutine to notify when wg is done waiting.
    time.Sleep(100 * time.Millisecond)
    go func() {
        wg.Wait()
        done <- struct{}{}
    }()

    select {
    case <-hasCycle:
        fmt.Println("got a cycle")
        return true
    case <-done:
        fmt.Println("no cycle detected")
        return false
    }
}

但是,这种方法让我担心,因为我需要睡眠,以便观察者仅在第一个 waitgroup 计数器增量之后才开始等待,这似乎比第一个解决方案脆弱得多。


正确答案


您是正确的,waitgroup 可能就是您想要的。但是,您没有正确使用它。首先,您需要在调用 wg.done() 的 go 例程之外调用 wg.add(1)。其次,调用 wg.wait() 会阻塞,直到等待组中的所有 go 例程完成执行,因此您不希望它同时执行。

至于短路,确实没有什么好办法。我的建议是使用上下文。在这种情况下,如果您想要真正的短路行为,您必须做的一件事是将上下文连接到 nodehascycle 的调用中。

修复您的代码,我们有:

func (c *cycleDet) hasCycle() bool {
    ctx, cancel := context.WithCancel(context.Background())
    hasCycle := make(chan bool)
    var wg sync.WaitGroup

    adj := c.b // adjacency list representation of the unerlying graph
    for node := range adj {
        wg.Add(1)
        go func(ctx context.Context, no nodeID, co chan<- bool, cancel context.CancelFunc) {
            // Use wg to synchronize termination of read-only goroutines.
            defer wg.Done()

            select {
                case <-ctx.Done():
                    return
                default:
            }

            visited := make(map[nodeID]struct{})
            // c.nodeHasCycle will use a recursive implementation of DFS to
            // find out if the node no leads to a cycle.
            if c.nodeHasCycle(ctx, no, visited) {
                co <- true
                cancel()
                return
            }
        }(ctx, node, hasCycle, cancel)
    }

    // Observer goroutine to notify when wg is done waiting.
    time.Sleep(100 * time.Millisecond)
    wg.Wait()
    defer cancel()

    select {
    case <-hasCycle:
        fmt.Println("got a cycle")
        return true
    default:
        fmt.Println("no cycle detected")
        return false
    }
}

通过这种方式设置,您可以确保对 go-routine 的所有调用都将运行,除非找到循环,在这种情况下,不会调用其他 go-routes,并且如果您添加逻辑来检查取消进入 nodehassycle,然后您也可以停止执行任何正在运行的调用。

终于介绍完啦!小伙伴们,这篇关于《如何判断一个 goroutine 成功还是所有 goroutine 都完成了?》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>