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

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

等待組。等待() 導致死鎖

等待組。等待() 導致死鎖

Go
胡子哥哥 2022-09-12 20:59:48
我試圖弄清楚為什么我有一個帶有等待組的死鎖。等待()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)    }}當我像這樣運行它時,它會打印fatal error: all goroutines are asleep - deadlock!我試圖更改為緩沖通道,這解決了問題。但我真的很想知道為什么會有死鎖。ch
查看完整描述

1 回答

?
慕碼人8056858

TA貢獻1803條經驗 獲得超6個贊

我已經注釋掉了程序邏輯不正確的部分:


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)

}


查看完整回答
反對 回復 2022-09-12
  • 1 回答
  • 0 關注
  • 81 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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