我有一个在 golang 中计算 SHA1 并打印以两个零开头的程序的程序。我想使用 goroutine 和通道。我的问题是,如果我不知道它会产生多少结果,我不知道如何优雅地退出 select 子句。
许多教程提前知道并在反击时退出。其他人建议使用 WaitGroups,但我不想这样做:我想在主线程中打印结果一出现在频道中。有人建议在 goroutines 完成时关闭通道,但我想在异步完成后关闭它,所以我不知道如何。
请帮助我实现我的要求:
package main
import (
"crypto/sha1"
"fmt"
"time"
"runtime"
"math/rand"
)
type Hash struct {
message string
hash [sha1.Size]byte
}
var counter int = 0
var max int = 100000
var channel = make(chan Hash)
var source = rand.NewSource(time.Now().UnixNano())
var generator = rand.New(source)
func main() {
nCPU := runtime.NumCPU()
runtime.GOMAXPROCS(nCPU)
fmt.Println("Number of CPUs: ", nCPU)
start := time.Now()
for i := 0 ; i < max ; i++ {
go func(j int) {
count(j)
}(i)
}
// close channel here? I can't because asynchronous producers work now
for {
select {
// how to stop receiving if there are no producers left?
case hash := <- channel:
fmt.Printf("Hash is %v\n ", hash)
}
}
fmt.Printf("Count of %v sha1 took %v\n", max, time.Since(start))
}
func count(i int) {
random := fmt.Sprintf("This is a test %v", generator.Int())
hash := sha1.Sum([]byte(random))
if (hash[0] == 0 && hash[1] == 0) {
channel <- Hash{random, hash}
}
}