登录
首页 >  Golang >  Go问答

使用渠道下单

来源:stackoverflow

时间:2024-02-25 21:18:24 368浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《使用渠道下单》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我有来自 gotour 的代码:

func sum(s []int, c chan int) {
    sum := 0
    for _, v := range s {
        sum += v
    }
    fmt.printf("sending %d to chan\n", sum)
    c <- sum // send sum to c
}

func main() {
    s := []int{2, 8, -9, 4, 0, 99}
    c := make(chan int)
    go sum(s[len(s)/2:], c)
    go sum(s[:len(s)/2], c)

    x, y := <-c, <-c // receive from c

    fmt.println(x, y, x+y)
}

产生此输出:

Sending 1 to chan
Sending 103 to chan
1 103 104

在此,x 获得第二个总和,y 获得第一个总和。为什么顺序颠倒了?


解决方案


类似于goroutines order of execution

如果多次运行,可能会得到不同的结果。当我运行这个时,我得到:

sending 103 to chan
sending 1 to chan
103 1 104

如果您希望结果是确定性的。您可以使用两个渠道:

func main() {
    s := []int{2, 8, -9, 4, 0, 99}

    c1 := make(chan int)
    c2 := make(chan int)
    go sum(s[len(s)/2:], c1)
    go sum(s[:len(s)/2], c2)

    x, y := <-c1, <-c2 // receive from c

    fmt.Println(x, y, x+y)
}

goroutines 的执行顺序无法保证。当您启动多个 goroutine 时,它​​们可能会也可能不会按照您期望的顺序执行,除非它们之间存在显式同步,例如通道或其他同步原语。

在你的例子中,第二个 goroutine 在第一个 goroutine 之前写入通道,因为没有机制来强制两个 goroutine 之间的排序。

终于介绍完啦!小伙伴们,这篇关于《使用渠道下单》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!

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