我是围棋学习者。为了更好地理解通道和 goroutine 的关心和馈送,我试图构建一个 Eratosthenes 筛,作为一组通过通道连接到管道中的 goroutine。
这是我到目前为止所拥有的:
// esieve implements a Sieve of Eratosthenes
// as a series of channels connected together
// by goroutines
package main
import "fmt"
func sieve(mine int, inch chan int) {
start := true // First-number switch
ouch := make(chan int) // Output channel for this instance
fmt.Printf("%v\n", mine) // Print this instance's prime
for next := <-inch; next > 0; next = <-inch { // Read input channel
fmt.Printf("%v <- %v\n",mine,next) // (Trace)
if (next % mine) > 0 { // Divisible by my prime?
if start { // No; is it the first number through?
go sieve(next, ouch) // First number - create instance for it
start = false // First time done
} else { // Not first time
ouch <- next // Pass it to the next instance
}
}
}
}
func main() {
lim := 30 // Let's do up to 30
fmt.Printf("%v\n", 2) // Treat 2 as a special case
ouch := make(chan int) // Create the first segment of the pipe
go sieve(3, ouch) // Create the instance for '3'
for prime := 3; prime < lim; prime += 2 { // Generate 3, 5, ...
fmt.Printf("Send %v\n", prime) // Trace
ouch <- prime // Send it down the pipe
}
}
就目前而言,它运行良好。
但是,当我完成主循环时,main在sieve实例管道中的所有数字传播到最后之前退出。
使主例程等待一组 goroutines(它只“知道”第一个)完成的最简单、最优雅或普遍接受的方法是什么?
波斯汪
狐的传说
相关分类