【问题标题】:how to understand the "ch=ch1" in the following codes?如何理解以下代码中的“ch=ch1”?
【发布时间】:2019-10-06 16:11:34
【问题描述】:

我无法理解“ch=ch1”的含义,为什么它可以打印素数?有人可以为我解释一下吗?我正在学习围棋。

    // Copyright 2009 The Go Authors. All rights reserved.
    // Use of this source code is governed by a BSD-style
    // license that can be found in the LICENSE file.package main
    package main

    import "fmt"

    // Send the sequence 2, 3, 4, ... to channel 'ch'.
    func generate(ch chan int) {
        for i := 2; ; i++ {
            ch <- i // Send 'i' to channel 'ch'.
        }
    }

    // Copy the values from channel 'in' to channel 'out',
    // removing those divisible by 'prime'.
    func filter(in, out chan int, prime int) {
    for {
        i := <-in // Receive value of new variable 'i' from 'in'.
        if i%prime != 0 {
            out <- i // Send 'i' to channel 'out'.
        }
    }
}

// The prime sieve: Daisy-chain filter processes together.
func main() {
    ch := make(chan int) // Create a new channel.
    go generate(ch)      // Start generate() as a goroutine.
    for {
        prime := <-ch
        fmt.Print(prime, " ")
        ch1 := make(chan int)
        go filter(ch, ch1, prime)
        ch = ch1
    }
}

有人可以为我解释一下这些代码吗?我已经学习了几天围棋。

【问题讨论】:

    标签: go channel goroutine


    【解决方案1】:

    ch 是“当前频道”。循环如下:

    1. 您从生成填充的通道开始。它是所有整数的通道。此频道的第一个数字是 2(质数)。
    2. 然后创建ch1,它是所有不能被2整除的整数的通道。
    3. = 是赋值运算符。通过使用ch = ch1,您是在告诉当前频道是所有不能被 2 整除的整数的频道。
    4. 新的循环迭代。当前频道的第一个数字是 3。您将 ch1 创建为当前频道,没有可被 3 整除的数字。
    5. 指定ch1为当前频道。所以现在当前频道是所有不能被 2 整除且不能被 3 整除的数字的频道。
    6. 重复

    【讨论】:

    • 在运行 ch=ch1 时,它会改变生成器函数中的数据吗?如果 ch=ch1 在 fliter 函数之前完成怎么办?因为我们无法保证 goroutine 的顺序和主进程中的代码。
    • generatefilter 以及它们所连接的频道都将永远运行。您只需添加更多具有更多通道的过滤器,然后打印第一个数字即可到达管道的末端。更改 ch 指向的内容对运行 filter 的 go-process 没有影响 - 该设置已在前一行完成。尝试用纸和铅笔完成它。
    猜你喜欢
    • 2019-03-17
    • 2023-04-02
    • 2013-12-12
    • 1970-01-01
    • 1970-01-01
    • 2020-01-03
    • 2015-03-10
    • 2017-03-19
    • 2017-02-03
    相关资源
    最近更新 更多