亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Goroutines:在哪里關閉

Goroutines:在哪里關閉

Go
慕婉清6462132 2022-06-06 17:49:01
我很難理解我應該在哪里關閉我的頻道。這段代碼大約需要 0.7 秒:options := [3]string{"0", "1", "2"}str := fmt.Sprintf("%6d ", id)for j := 0; j < 40000; j++ {    str += options[rand.Intn(3)]}str += "\n"添加 io.Writestring 對時間沒有影響,所以問題出在這一點。我想要大約 100,000 條這樣的記錄,所以我想放入一個 goroutine。func main() {    file, _ := os.Create("myfile.txt")    ch := make(chan string)    for i := 0; i < 100000; i++ {       go generate(i, ch)    }    counter := 0    for result := range ch {       counter++       io.WriteString(file, result)       if counter == 100000 {           close(ch)       }    }    file.Close()}func generate(id int, c chan string) {    options := [3]string{"0", "1", "2"}    str := fmt.Sprintf("%6d ", id)    for j := 0; j < 40000; j++ {        str += options[rand.Intn(3)]    }    str += "\n"    c <- str}據我了解,我正在關閉接收方的通道,這并不理想?此外,這樣所有 100,000 應該首先發送到 goroutines,然后我才能收到任何。我可以發送請求以生成記錄并同時開始接收嗎?
查看完整描述

2 回答

?
qq_遁去的一_1

TA貢獻1725條經驗 獲得超8個贊

使用計數器關閉您的頻道不是一個好習慣。您可以使用sync.WaitGroup. 這使您可以更好地控制何時關閉頻道:


func main() {


    var wg sync.WaitGroup


    ch := make(chan string)

    file, _ := os.Create("myfile.txt")


    for i := 0; i < 100000; i++ {

        wg.Add(1)


        go func(i int) {

            defer wg.Done()


            options := [3]string{"0", "1", "2"}

            str := fmt.Sprintf("%6d ", i)

            for j := 0; j < 40000; j++ {

                str += options[rand.Intn(3)]

            }

            str += "\n"

            ch <- str

        }(i)

    }


    go func() {

        wg.Wait()

        close(ch)

    }()


    for result := range ch {

        io.WriteString(file, result)

    }

    file.Close()

}


查看完整回答
反對 回復 2022-06-06
?
POPMUISE

TA貢獻1765條經驗 獲得超5個贊

看看能不能解決你的問題。。


func main() {

    file, _ := os.Create("myfile.txt")

    ch := make(chan string)

    wg := new(sync.WaitGroup)

    for i := 0; i < 100000; i++ {

       wg.Add(1)

       go generate(i, ch)

    }


    go func(){wg.Wait();close(ch)}()


    counter := 0

    for result := range ch {

       counter++

       io.WriteString(file, result)


    }

    file.Close()

}


func generate(id int, c chan string) {

    options := [3]string{"0", "1", "2"}

    str := fmt.Sprintf("%6d ", id)

    for j := 0; j < 40000; j++ {

        str += options[rand.Intn(3)]

    }

    str += "\n"

    c <- str

    wg.Done()

}


查看完整回答
反對 回復 2022-06-06
  • 2 回答
  • 0 關注
  • 145 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號