GO 频道突然结束?

我正在尝试使用 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


慕婉清6462132
浏览 66回答 1
1回答

蓝山帝景

你的逻辑有错误: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 +=
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go