douti9253 2016-01-13 07:05
浏览 65
已采纳

如何在同一循环中向通道发送值或从通道接收值?

Here is an example:

func main() {
    c := make(chan int)
    i := 0

    go goroutine(c)

    c <- i
    time.Sleep(10 * time.Second)

}

func goroutine(c chan int) {
    for {
        num := <- c
        fmt.Println(num)
        num++
        time.Sleep(1 * time.Second)
        c <- num
    }
}

What I'm trying to do inside of goroutine is to receive number from channel, print it, increment and after one second send it back to the channel. After this I want to repeat the action.

But as a result, operation is only done once.

Output:

0

Am I doing something wrong?

  • 写回答

3条回答 默认 最新

  • drgzmmy6379 2016-01-13 07:21
    关注

    By default the goroutine communication is synchronous and unbuffered: sends do not complete until there is a receiver to accept the value. There must be a receiver ready to receive data from the channel and then the sender can hand it over directly to the receiver.

    So channel send/receive operations block until the other side is ready:

    1. A send operation on a channel blocks until a receiver is available for the same channel: if there’s no recipient for the value on ch, no other value can be put in the channel. And the other way around: no new value can be sent in ch when the channel is not empty! So the send operation will wait until ch becomes available again.

    2. A receive operation for a channel blocks until a sender is available for the same channel: if there is no value in the channel, the receiver blocks.

    This is illustrated in the below example:

    package main
    import "fmt"
    
    func main() {
        ch1 := make(chan int)
        go pump(ch1) // pump hangs
        fmt.Println(<-ch1) // prints only 0
    }
    
    func pump(ch chan int) {
        for i:= 0; ; i++ {
            ch <- i
        }
    }
    

    Because there is no receiver the goroutine hangs and print only the first number.

    To workaround this we need to define a new goroutine which reads from the channel in an infinite loop.

    func receive(ch chan int) {
        for {
            fmt.Println(<- ch)
        }
    }
    

    Then in main():

    func main() {
        ch := make(chan int)
        go pump(ch)
        go receive(ch)
    }
    

    <kbd>Go Playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA