带channel 的素数筛选法!

qkb_75_go · 2014-12-04 12:05:07 · 2041 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2014-12-04 12:05:07 的主题,其中的信息可能已经有所发展或是发生改变。

我不久前刚刚写了一个素数筛选法,http://studygolang.com/topics/556

基本是C语言的思路

不过今天我刚刚看到这个经典的CSP的代码

完全是 GO的风格! http://tonybai.com/tag/go/page/2/

刚开始我没有看懂,自己运行一下,居然可以连续输出素数!

不由得我对这段代码兴趣大增!反复看,终于明白了它的执行过程,心中的高兴劲别提了! 好久没有这样兴奋过了!

开始仔细琢磨 GO的代码语境,真的很带劲的代码!

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 'src' to channel 'dst',
// removing those divisible by 'prime'.
func filter(src <-chan int, dst chan<- int, prime int) {
    for i := range src {  // Loop over values received from 'src'.
        if i%prime != 0 {
            dst <- i  // Send 'i' to channel 'dst'.
        }
    }
}
// The prime sieve: Daisy-chain filter processes together.
func sieve() {
    ch := make(chan int)  // Create a new channel.
    go generate(ch)       // Start generate() as a subprocess.
    for {
        prime := <-ch
        fmt.Print(prime, "\n")
        ch1 := make(chan int)
        go filter(ch, ch1, prime)
        ch = ch1
    }
}
func main() {
    sieve()
}

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2041 次点击  
加入收藏 微博
3 回复  |  直到 2014-12-11 11:52:11
blov
blov · #1 · 10年之前

貌似官方给的例子就有这个。

renpei1992
renpei1992 · #2 · 10年之前

range src(receive from send only type chan<- int)

renpei1992
renpei1992 · #3 · 10年之前
renpei1992renpei1992 #2 回复

range src(receive from send only type chan<- int)

哦,找到原因了。还不是很了解channel

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传