登录
首页 >  Golang >  Go问答

Goroutines 的意外行为

来源:stackoverflow

时间:2024-03-22 22:15:45 158浏览 收藏

在 Go 并发编程中,使用 Goroutine 进行异步任务处理时,可能会遇到意想不到的行为。本文探讨了一个使用 Goroutine 的示例,其中第一个 Goroutine 未被执行,尽管第二个 Goroutine 已完成。分析了这个问题,解释了 select 语句和 for 循环中止条件的正确用法,以确保所有 Goroutine 正确执行。

问题内容

我是 golang 初学者

我正在从这里阅读有关 go 并发的内容。

一切进展顺利,直到我收到第 8 张幻灯片上的问题。

问题是:找出两个给定的二叉树是否等价。

我的方法:进行中序遍历,将两棵树的值保存在一个切片中并进行比较。

这是我的解决方案:[不完整]

package main

import (
    "fmt"
    "golang.org/x/tour/tree"
)

// walk walks the tree t sending all values
// from the tree to the channel ch.
func walk(t *tree.tree, ch chan int) {
    if t != nil {
        walk(t.left, ch)
        ch <- t.value
        walk(t.right, ch)
    }
}

// same determines whether the trees
// t1 and t2 contain the same values.
func same(t1, t2 *tree.tree) bool {
    ch1 := make(chan int)
    ch2 := make(chan int)

    go func() {
        fmt.println("executing first go routing")
        walk(t1, ch1)
        fmt.println("closing channel [ch1]")
        close(ch1)
    }()

    go func() {
        fmt.println("executing second go routing")
        walk( t2, ch2 )
        fmt.println("closing channel [ch2]")
        close(ch2)
    }()

    shouldcontinue := true
    var continue1, continue2 bool
    for shouldcontinue {
        select {
        case r1, ok1 := <-ch1:
            fmt.println("[ch1] [rcvd]", r1)
            continue1 = ok1

        case r2, ok2 := <-ch2:
            fmt.println("[ch2] [rcvd]", r2)
            continue2 = ok2
        }
        shouldcontinue = continue1 || continue2
    }
    return true
}

func main() {
    same(tree.new(1), tree.new(1))
}

我知道 goroutine 是协作调度的,如果一个 goroutine 正在循环或连续进行计算,那么它会完全阻塞另一个 goroutine。因此,我预计对于输出,它将首先接收来自任一通道的值,关闭它,然后它将接收来自另一个通道的值,然后关闭。一旦两者都关闭,for 循环就会中断。

令我惊讶的是,第一个 go 例程从未被安排。这是我收到的输出:

executing second go routing
[ch2] [rcvd] 1
[ch2] [rcvd] 2
[ch2] [rcvd] 3
[ch2] [rcvd] 4
[ch2] [rcvd] 5
[ch2] [rcvd] 6
[ch2] [rcvd] 7
[ch2] [rcvd] 8
[ch2] [rcvd] 9
[ch2] [rcvd] 10
closing channel [ch2]
[ch2] [rcvd] 0

谁能解释一下这是怎么回事?一旦通道2关闭并且第二个go例程完成,为什么第一个例程不被执行?

如有任何帮助,我们将不胜感激。谢谢。

更新:

我在谷歌上搜索了有关突破频道的信息,并在这里找到了一个问题。 据此,我更新了我的解决方案如下:

package main

import (
    "fmt"
    "golang.org/x/tour/tree"
    // "time"
)

// walk walks the tree t sending all values
// from the tree to the channel ch.
func walk(t *tree.tree, ch chan int) {
    // time.sleep(time.millisecond)
    if t != nil {
        walk(t.left, ch)
        ch <- t.value
        walk(t.right, ch)
    }
}

// same determines whether the trees
// t1 and t2 contain the same values.
func same(t1, t2 *tree.tree) bool {
    ch1 := make(chan int)
    ch2 := make(chan int)

    go func() {
        fmt.println("executing first go routing")
        walk(t1, ch1)
        fmt.println("closing channel [ch1]")
        close(ch1)
    }()

    go func() {
        fmt.println("executing second go routing")
        walk( t2, ch2 )
        fmt.println("closing channel [ch2]")
        close(ch2)
    }()

    for {
        select {
        case r1, ok1 := <-ch1:
            fmt.println("[ch1] [rcvd]", r1)
            if !ok1 {
                ch1 = nil
            } 

        case r2, ok2 := <-ch2:
            fmt.println("[ch2] [rcvd]", r2)
            if !ok2 {
                ch2 = nil
            }
        }
        if ch1 == nil && ch2 == nil {
            break
        }
    }
    return true
}

func main() {
    same(tree.new(1), tree.new(1))
}

这给出了我认为第一个片段的确切输出:

executing second go routing
[ch2] [rcvd] 1
[ch2] [rcvd] 2
[ch2] [rcvd] 3
[ch2] [rcvd] 4
[ch2] [rcvd] 5
[ch2] [rcvd] 6
[ch2] [rcvd] 7
[ch2] [rcvd] 8
[ch2] [rcvd] 9
[ch2] [rcvd] 10
closing channel [ch2]
[ch2] [rcvd] 0
executing first go routing
[ch1] [rcvd] 1
[ch1] [rcvd] 2
[ch1] [rcvd] 3
[ch1] [rcvd] 4
[ch1] [rcvd] 5
[ch1] [rcvd] 6
[ch1] [rcvd] 7
[ch1] [rcvd] 8
[ch1] [rcvd] 9
[ch1] [rcvd] 10
closing channel [ch1]
[ch1] [rcvd] 0

我现在对发生的事情更加困惑。


解决方案


一旦通道2关闭,为什么第一个通道不被执行?

通道未执行。一遍又一遍执行的内容是您的选择。请注意,无论通道是否关闭,这两种情况都可以始终执行。因此, select 选择 id 执行的第二种情况并且您中止是可以的。 (您的中止条件看起来很可疑:一旦两个通道都关闭,即如果两个 ok1和ok2都为假,您就完成了。

不要将 select 视为“goroutine 调度工具”本身。它不是。它将随机选择一个可运行案例。如果所有案例的形式均为 val, ok := <- ch ,那么所有案例都可以运行,并且 select 可能始终选择第二个。或者是第一个,或者...

[第二个解决方案]我现在对发生的事情更加困惑。

您的中止条件不同。一旦两个通道都为零,就会中断,这会在两个通道都关闭后发生。这与您的第一个解决方案不同,因为一旦任何一个通道关闭,第一个解决方案就会中断。

这里的并发问题不是 goroutine 调度,而是 for 循环执行选择的中止条件。它们与第一个和第二个不同,第一个从根本上来说是错误的,因为一旦任何通道耗尽它就会停止。

在代码的第一部分中,您的逻辑存在错误。

shouldcontinue := true
var continue1, continue2 bool
for shouldcontinue {
    select {
    case r1, ok1 := <-ch1:
        fmt.println("[ch1] [rcvd]", r1)
        continue1 = ok1

    case r2, ok2 := <-ch2:
        fmt.println("[ch2] [rcvd]", r2)
        continue2 = ok2
    }
    shouldcontinue = continue1 || continue2
}

在上面的代码中,continue1continue2falseselect 正在阻塞,直到他的案例之一得到满足。可以说 case r2, ok2 := <-ch2: 首先满足,然后 continue2 将是 true。因为shouldcontinue = continue1 || continue2 这个条件下,for 循环会继续。由于某种原因(进行例程调度) case r2, ok2 := <-ch2: 条件每次都满足。现在,当 ch2 关闭时,ok2 的值将为 false,因此 continue2 也将为 false。现在,continue1continue2 都是 false,因此 shouldcontinue 也将是 false。因此,它打破了 for 循环,并且您看不到 ch1 的输出。试试这个:

continue1 = true
continue2 = true
for shouldContinue {
    select {
    case r1, ok1 := <-ch1:
        fmt.Println("[ch1] [rcvd]", r1)
        continue1 = ok1

    case r2, ok2 := <-ch2:
        fmt.Println("[ch2] [rcvd]", r2)
        continue2 = ok2
    }
    shouldContinue = continue1 || continue2
}

零通道始终处于阻塞状态,并且您还更改了 for 循环中断逻辑。这就是您的第二个解决方案有效的原因。

好了,本文到此结束,带大家了解了《Goroutines 的意外行为》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

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