首页 > 其他 > 详细

用Go的风格实现素数筛选

时间:2017-07-21 13:11:05      阅读:346      评论:0      收藏:0      [点我收藏+]
package main

import (
    "fmt"
    "time"
)

const End = 10000

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

func validate(in <-chan int, out chan<- int, fix int) {
    for {
        select {
        case i := <-in:
            if i%fix != 0 {
                out <- i
            }
        case <-time.After(50 * time.Millisecond):
            close(out)
            return
        }
    }
}

// 打印素数
func main() {

    // 逐个获取待检测的数据源
    ch := make(chan int)
    go source(ch)

    for {
        data, ok := <-ch
        if !ok {
            break
        }
        fmt.Println(data)
        out := make(chan int)
        go validate(ch, out, data)
        ch = out
    }
}

 参考:http://tonybai.com/2017/04/20/go-coding-in-go-way/ , 但他实现的没有关闭chan, 导致 fatal error: all goroutines are asleep - deadlock! ,本方法优化了这个BUG.

技术分享技术分享

 

用Go的风格实现素数筛选

原文:http://www.cnblogs.com/logo-fox/p/7216996.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!