用Go的风格实现素数筛选

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(1 * time.Second):
            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.

原文地址:https://www.cnblogs.com/logo-fox/p/7216996.html