我正在嘗試使用 go 通道同時生成帳戶(下面是簡化的代碼),但是我看到它并沒有生成所有帳戶:package mainimport ( "fmt" "github.com/segmentio/ksuid")const ConcurrencyLevel = 10const TotalAccounts = 30type ( 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 : 30total accounts generated is : 20在這種情況下,預計生成的帳戶總數為 30。https://go.dev/play/p/UtFhE2nidaP
GO 頻道突然結束?
慕婉清6462132
2022-11-08 16:06:57