我正在尝试使用 go 通道同时生成帐户(下面是简化的代码),但是我看到它并没有生成所有帐户:
package main
import (
"fmt"
"github.com/segmentio/ksuid"
)
const ConcurrencyLevel = 10
const TotalAccounts = 30
type (
Accounts []Account
Account struct {
AccountID string
}
)
func GenerateRandomAccountID() (accountReferenceID string){
return ksuid.New().String()
}
func main() {
totalAccounts := make(Accounts, 0, TotalAccounts)
total := 0
for total < TotalAccounts {
accounts := make([]Account, ConcurrencyLevel)
ch := make(chan Account)
for range accounts {
go func() {
accountID := GenerateRandomAccountID()
account := Account{AccountID: accountID}
ch <- account
}()
}
for k, _ := range accounts {
account := <-ch
accounts[k] = account
}
totalAccounts = append(totalAccounts, accounts...)
total += len(totalAccounts)
close(ch)
}
fmt.Printf("total is : %d\n", total)
fmt.Printf("total accounts generated is : %d\n", len(totalAccounts))
}
它打印出来
total is : 30
total accounts generated is : 20
在这种情况下,预计生成的帐户总数为 30。
https://go.dev/play/p/UtFhE2nidaP
蓝山帝景
相关分类