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

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

預期輸出以及工作池中的死鎖

預期輸出以及工作池中的死鎖

Go
滄海一幻覺 2023-01-03 15:53:33
我正在學習 Go 并發并編寫了強制性工作池示例,其中有 N 個工作和 M 個工作人員(N > M)。我遇到了一個死鎖 ( all goroutines are asleep),我想不通;但是,我也在死鎖發生之前得到了預期的輸出,這讓我更加困惑。有人可以指出我做錯了什么嗎?我的代碼是這樣的:package mainimport (    "fmt"    "sync")// A simple worker pool implementation using channels and WaitGroups.// Our workers simply read from a channel of integers from an input// channel and write their squares to an output channel.func addJobs(jobsCh chan<- int, wg *sync.WaitGroup) {    // 100 numbers to crunch (jobs)    for i := 1; i < 101; i++ {        jobsCh <- i    }    wg.Done()}func worker(jobsCh <-chan int, resultsCh chan<- int, wg2 *sync.WaitGroup) {    for num := range jobsCh {        resultsCh <- num * num    }    wg2.Done()}func addWorkers(jobsCh <-chan int, resultsCh chan<- int, wg *sync.WaitGroup) {    var wg2 sync.WaitGroup    // 10 workers    for i := 0; i < 10; i++ {        wg2.Add(1)        go worker(jobsCh, resultsCh, &wg2)    }    wg.Done()}func readResults(resultsCh <-chan int, wg *sync.WaitGroup) {    for sq := range resultsCh {        fmt.Printf("%v ", sq)    }    wg.Done()}func main() {    var wg sync.WaitGroup    jobsCh := make(chan int)    resultsCh := make(chan int)    wg.Add(1)    go addJobs(jobsCh, &wg)    wg.Add(1)    go addWorkers(jobsCh, resultsCh, &wg)    wg.Add(1)    go readResults(resultsCh, &wg)    wg.Wait()}正如預期的那樣,這會打印數字的平方(以隨機順序),但也會遇到死鎖。請參閱此游樂場鏈接。:(
查看完整描述

1 回答

?
九州編程

TA貢獻1785條經驗 獲得超4個贊

關閉jobsCh導致工人退出:


func addJobs(jobsCh chan<- int, wg *sync.WaitGroup) {

    // 100 numbers to crunch (jobs)

    for i := 1; i < 101; i++ {

        jobsCh <- i

    }

    close(jobsCh)  // <-- add this line

    wg.Done()

}

工作人員完成后,關閉resultsCh導致結果循環退出:


func addWorkers(jobsCh <-chan int, resultsCh chan<- int, wg *sync.WaitGroup) {

    var wg2 sync.WaitGroup

    // 10 workers

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

        wg2.Add(1)

        go worker(jobsCh, resultsCh, &wg2)

    }

    wg2.Wait()       // <-- add this line

    close(resultsCh) // and this line

    wg.Done()

}


查看完整回答
反對 回復 2023-01-03
  • 1 回答
  • 0 關注
  • 88 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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