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

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

致命錯誤:所有 goroutines 都睡著了——死鎖!錯誤GO

致命錯誤:所有 goroutines 都睡著了——死鎖!錯誤GO

Go
慕桂英3389331 2023-03-21 10:35:51
我是 Go 并發的新手,所以我嘗試了一個帶有通道和 goroutines 的例子。我想要生產者消費者模式。生產者函數永遠提供隨機字符串,消費者通過將它們變成大寫來修改它們。我想在有限的時間內(2 秒)運行它。package mainimport (    "fmt"    "math/rand"    "strings"    "time")func producer(x []string, c chan string) {    i := 1    for i > 0 {        randomIndex := rand.Intn(len(x))        pick := x[randomIndex]        c <- pick    }}func consumer(x string, c chan string) {    x1 := strings.ToUpper(x)    c <- x1}func main() {    s := []string{"one", "two", "three", "four"}    c1 := make(chan string)    d1 := make(chan string)    go producer(s, c1)    go consumer(<-c1, d1)    stop := time.After(2000 * time.Millisecond)    for {        select {        case <-stop:            fmt.Println("STOP AFTER 2 SEC!")            return        default:            fmt.Println(<-d1)            time.Sleep(50 * time.Millisecond)        }    }}我只得到一個數組元素和一些錯誤。需要進行哪些更改才能使此示例有效?輸出:二致命錯誤:所有 goroutines 都睡著了——死鎖!goroutine 1 [chan receive]: main.main()goroutine 6 [chan send]: main.producer({0xc00004e040, 0x4, 0x0?}, 0x0?) 由 main 創建。主要退出狀態 2
查看完整描述

1 回答

?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

您的消費者應該循環運行,這已經提到過。


更改消費者的第一個參數,使其為 achan string而不是字符串。這樣生產者就可以不斷地寫入這個通道,讓消費者在另一個通道上發布,直到時間限制到期。


func consumer(consumeChan chan string, outCh chan string) {

    for {

        select {

        case s := <- consumeChan:

            s = strings.ToUpper(s)

            outCh <- s

        }

    }

}

現在在go consumer()調用之前的 main func 中,您正在等待c1生產者對頻道的第一個響應。c1而不是將通道作為第一個參數傳遞。


func main() {

    s := []string{"one", "two", "three", "four"}

    c1 := make(chan string)

    d1 := make(chan string)

    go producer(s, c1)

    go consumer(c1, d1)


    stop := time.After(2000 * time.Millisecond)

    for {

        select {

        case <-stop:

            fmt.Println("STOP AFTER 2 SEC!")

            return

        case response := <- d1:

            fmt.Println(response)

            time.Sleep(50 * time.Millisecond)

        }

    }

}

這應該向您展示生產者在通道上連續寫入隨機數c1,以及消費者在 d1 通道上連續寫入所有大寫文本,直到 2 秒結束。


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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