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条)

报告相同问题?

悬赏问题

  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥30 用arduino开发esp32控制ps2手柄一直报错
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿