第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

等待組。等待() 導(dǎo)致死鎖

等待組。等待() 導(dǎo)致死鎖

Go
胡子哥哥 2022-09-12 20:59:48
我試圖弄清楚為什么我有一個(gè)帶有等待組的死鎖。等待()package mainimport (    "fmt"    "sync")var wg sync.WaitGroupfunc foo(c chan int, i int) {    defer wg.Done()    c <- i}func main() {    ch := make(chan int)    for i := 0; i < 10; i++ {        wg.Add(1)        go foo(ch, i)    }    wg.Wait()    close(ch)    for item := range ch {        fmt.Println(item)    }}當(dāng)我像這樣運(yùn)行它時(shí),它會(huì)打印fatal error: all goroutines are asleep - deadlock!我試圖更改為緩沖通道,這解決了問題。但我真的很想知道為什么會(huì)有死鎖。ch
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻(xiàn)1803條經(jīng)驗(yàn) 獲得超6個(gè)贊

我已經(jīng)注釋掉了程序邏輯不正確的部分:


package main


import (

    "fmt"

    "sync"

)


var wg sync.WaitGroup


func foo(c chan int, i int) {

    defer wg.Done()

    c <- i

}


func main() {

    ch := make(chan int) // unbuffered channel


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

        wg.Add(1)

        go foo(ch, i)

    }


    // wg.Wait is waiting for all goroutines to finish but that's

    // only possible if the send to channel succeeds. In this case,

    // it is not possible as your receiver "for item := range ch" is below

    // this. Hence, a deadlock.

    wg.Wait()


    // Ideally, it should be the sender's duty to close the channel.

    // And closing a channel before the receiver where the channel

    // is unbuffered is not correct.

    close(ch)


    for item := range ch {

        fmt.Println(item)

    }

}

更正的程序:


package main


import (

    "fmt"

    "sync"

)


var wg sync.WaitGroup


func foo(c chan int, i int) {

    defer wg.Done()

    c <- i

}


func main() {

    ch := make(chan int)


    go func() {

        for item := range ch {

            fmt.Println(item)

        }

    }()


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

        wg.Add(1)

        go foo(ch, i)

    }


    wg.Wait()

    close(ch)

}


查看完整回答
反對(duì) 回復(fù) 2022-09-12
  • 1 回答
  • 0 關(guān)注
  • 80 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)