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

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

帶通道的簡(jiǎn)單并行示例,導(dǎo)致死鎖

帶通道的簡(jiǎn)單并行示例,導(dǎo)致死鎖

Go
Helenr 2022-08-01 10:31:38
我正在嘗試使用通道在golang中實(shí)現(xiàn)一個(gè)簡(jiǎn)單的并行化示例。代碼嘗試實(shí)現(xiàn)并行映射函數(shù)。使通道也進(jìn)行了緩沖,以減輕對(duì)通道阻塞性質(zhì)的約束。但代碼仍然會(huì)導(dǎo)致死鎖。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)}從上面代碼的輸出中,我得到死鎖是因?yàn)橥ǖ垒敵鯷1]從未被讀取。但我不知道為什么0 1010 20goroutine started with  0 10goroutine started with  10 20567891011121314fatal error: all goroutines are asleep - deadlock!
查看完整描述

1 回答

?
胡說(shuō)叔叔

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

問(wèn)題在于,在通道關(guān)閉之前,通過(guò)通道不斷嘗試從通道接收,但在完成發(fā)送后您沒(méi)有通道。rangeclose

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

游樂(lè)場(chǎng): https://play.golang.org/p/NbKTx6Lke7X

編輯:修復(fù)了關(guān)閉已關(guān)閉頻道的錯(cuò)誤。


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

添加回答

舉報(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)