我正在尝试使用 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
1 回答
蓝山帝景
TA贡献1843条经验 获得超7个赞
你的逻辑有错误:
totalAccounts = append(totalAccounts, accounts...)
total += len(totalAccounts)
假设这是循环的第二次迭代。totalAccounts已经包含 10 个项目,您再添加 10 个,因此长度现在为 20。然后您取total(从第一次运行开始将是 10)并添加len(totalAccounts)(20) 以得到 30 的结果。这意味着您的循环 ( for total < TotalAccounts) 完成早于应有的。
要解决此问题,您可以使用playground:
totalAccounts = append(totalAccounts, accounts...)
total += len(accounts) // Add the number of NEW accounts
或者
totalAccounts = append(totalAccounts, accounts...)
total = len(totalAccounts ) // = not +=
- 1 回答
- 0 关注
- 65 浏览
添加回答
举报
0/150
提交
取消