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

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

拋出:所有goroutine都在睡覺-死鎖

拋出:所有goroutine都在睡覺-死鎖

Go
DIEA 2021-05-11 17:53:39
給出以下簡單的Go程序package mainimport (    "fmt")func total(ch chan int) {    res := 0    for iter := range ch {        res += iter    }    ch <- res}func main() {    ch := make(chan int)    go total(ch)    ch <- 1    ch <- 2    ch <- 3    fmt.Println("Total is ", <-ch)}我想知道有人能否啟發我throw: all goroutines are asleep - deadlock!謝謝你
查看完整描述

2 回答

?
森欄

TA貢獻1810條經驗 獲得超5個贊

由于您從不關閉ch通道,因此范圍循環將永遠不會結束。


您無法在同一頻道上發送結果。一種解決方案是使用不同的解決方案。


您的程序可以像這樣進行修改:


package main


import (

    "fmt"

)


func total(in chan int, out chan int) {

    res := 0

    for iter := range in {

        res += iter

    }

    out <- res // sends back the result

}


func main() {

    ch := make(chan int)

    rch  := make(chan int)

    go total(ch, rch)

    ch <- 1

    ch <- 2

    ch <- 3

    close (ch) // this will end the loop in the total function

    result := <- rch // waits for total to give the result

    fmt.Println("Total is ", result)

}


查看完整回答
反對 回復 2021-05-17
  • 2 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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