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

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

去通道不輸出它傳遞的數據

去通道不輸出它傳遞的數據

Go
喵喵時光機 2022-10-24 16:19:37
我是新手,我正在嘗試頻道并發現了這一點。func main() {    c := make(chan int)    fmt.Println("initialized channel")    go receiver(c)    go helper(c)    for x := range c {        fmt.Println(x)    }}func helper(c chan int) {    time.Sleep(time.Second * 3)    c <- 5    time.Sleep(time.Second * 3)    c <- 4    close(c)}func receiver(c chan int) {    for x := range c {        fmt.Println(x)    }}問題是即使我發送了兩個號碼,但控制臺中只打印了一個號碼。initialized channel5輸出
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

行為無法預測。有時您的程序會工作,有時則不會。我已經解釋了問題發生的代碼(帶有注釋)。


package main


import (

    "fmt"

    "time"

)


func main() {

    c := make(chan int)

    fmt.Println("initialized channel")


    // This is a receiver receiving from c (spawned goroutine)

    go receiver(c)

    // This is a sender (spawned goroutine)

    go helper(c)


    // This is again a receiver receiving from c

    // NOTE: As reciever and helper are spawned in

    // separate goroutine, control eventually reaches

    // here.

    // Behaviour is unpredictable as sometimes the data

    // sent to the channel might be recieved here and

    // sometimes it might be recieved by the receiver function.

    for x := range c {

        fmt.Println(x)

    }

}


func helper(c chan int) {

    time.Sleep(time.Second * 3)

    c <- 5

    time.Sleep(time.Second * 3)

    c <- 4


    // When this close is triggered, the receiver in main

    // could get exited as the signal to stop ranging is sent

    // using signal. Right after that the main function ends

    // such that data recieved by the receiver couldn't get

    // printed (sometimes it would work as well) i.e., main

    // exited right before fmt.Println(x) in receiver function.

    close(c)

}


func receiver(c chan int) {

    for x := range c {

        fmt.Println(x)

    }

}

要修復它,你可以試試這個。還有更多可能的解決方案,但這已經足夠了。我已經刪除了time.Sleep電話,因為它們與我們無關并且為簡潔起見。


package main


import (

    "fmt"

)


func main() {

    // Initialize the channel

    c := make(chan int)


    // Spawn a goroutine that sends data to the

    // channel. Also, it is expected from the sender

    // only to close the channel as it only knows

    // when then send stops. Send to a closed

    // channel would panic.

    go send(c)


    // As send is running asynchronously, control

    // reaches here i.e., the receiver. It ranges until

    // c is closed and is guaranteed to receive every

    // date sent to channel c and then exit.

    for x := range c {

        fmt.Println(x)

    }

}


// send data to c

func send(c chan int) {

    c <- 5

    c <- 4

    close(c)

}


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

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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