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

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

帶通道的簡單并行示例,導致死鎖

帶通道的簡單并行示例,導致死鎖

Go
夢里花落0921 2022-07-25 10:38:00
我正在嘗試使用通道在 golang 中實現一個簡單的并行化示例。該代碼嘗試實現并行化的映射函數。也使通道緩沖以緩解對通道阻塞性質的限制。但是代碼仍然會導致死鎖。func pmmap(inp []int, f func(int) int, p int) {    var wg sync.WaitGroup    var output []chan int    tot := len(inp)    out := make(chan int, tot)    slice := tot / p    for i := 0; i < p; i++ {        temp := make(chan int, slice)        output = append(output, temp)        start_ind := slice * i        end_ind := start_ind + slice        fmt.Println(start_ind, end_ind)        wg.Add(1)        go func(si, ei int, out chan int, wg *sync.WaitGroup) {            fmt.Println("goroutine started with ", si, ei)            for ind := si; ind < ei; ind++ {                out <- f(inp[ind])            }            wg.Done()        }(start_ind, end_ind, output[i], &wg)    }    wg.Add(1)    go func(wg *sync.WaitGroup) {        for i := 0; i < p; i++ {            for val := range output[i] {                out <- val            }            close(output[i])        }        wg.Done()    }(&wg)    wg.Add(1)    go func(wg *sync.WaitGroup) {        for i := range out {            fmt.Println(i)        }        wg.Done()    }(&wg)    time.Sleep(time.Second * 6)    wg.Wait()    close(out)}func add4(i int) int {    return i + 4}func main() {    temp := []int{}    for i := 1; i <= 20; i++ {        temp = append(temp, i)    }    pmmap(temp, add4, 2)}從上面代碼的輸出中,我得到死鎖是因為通道輸出 [1] 永遠不會被讀取。但我不知道為什么0 1010 20goroutine started with  0 10goroutine started with  10 20567891011121314fatal error: all goroutines are asleep - deadlock!
查看完整描述

1 回答

?
慕容森

TA貢獻1853條經驗 獲得超18個贊

問題是通過一個通道不斷嘗試從通道接收,直到通道關閉,但完成發送后range您沒有通道。close

在您的代碼中添加close(out)之前wg.Done將修復它。

游樂場: https: //play.golang.org/p/NbKTx6Lke7X

編輯:修復了關閉封閉頻道的錯誤。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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