doutuo1939 2014-08-28 12:42
浏览 42
已采纳

在此示例中渠道如何工作?

This is is an example of prime number sieve

package main

func Generate(ch chan<- int) {
  for i := 2; ; i++ {
    ch <- i
  }
}

func Filter(in <-chan int, out chan<- int, prime int) {
  for {
    i := <-in
    if i%prime != 0 {
      out <- i
    }
  }
}

func main() {
  ch := make(chan int)
  go Generate(ch)
  for i := 0; i < 10; i++ {
    prime := <-ch
    print(prime, "
")
    ch1 := make(chan int)
    go Filter(ch, ch1, prime)
    ch = ch1
  }
}

What I understand is this line of code

prime := <-ch

the channel is waiting for an input and assigns to prime. So, why all the numbers are not printed when the next statement is called

print(prime, "
")

If I remove these last 3 lines

ch1 := make(chan int)
go Filter(ch, ch1, prime)
ch = ch1

then all numbers are printed from 2 to 11. What does this line do ch = ch1?

Thanks

  • 写回答

2条回答 默认 最新

  • 普通网友 2014-08-29 08:14
    关注

    Your code's output is :

    2
    3
    5
    7
    11
    13
    17
    19
    23
    29
    

    So the procedure is like this :

    i=0,

    after prime := <-ch , prime=2, ch = {3};

    after go Filter(ch, ch1, prime) , mark as Filter0,in function Filter0 channel in will be 3,4,5,6 ... and channel out will be 3,5,7 ...;

    After ch = ch1, So ch = {3}, which will be 3,5,7.

    i=1,

    after prime := <-ch ,prime= 3, ch ={5},why is there 5 in ch?'Cause now ch is the ch1 in last loop ;

    after go Filter(ch, ch1, prime) , mark as Filter1,in function Filter1 channel in will be 5,7,9,11 ... and channel out will be 5,7,11 ...;

    After ch = ch1, So ch = {3}, which will be 5,7,11.

    i=2, the same .

    That how it output.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路