dpxkkhu1812 2017-01-23 11:04
浏览 70
已采纳

Golang并发和单个通道阻塞,需要解释

I'm playing around with the code presented on https://tour.golang.org/concurrency/5. My idea was that I could simplify the code by getting rid of the quit channel and still keep the correct program behavior - just for learning purposes.

Here is the code I've got (simplified it even more for better readability):

package main

import "fmt"
import "time"

func sendNumbers(c chan int) {  
    for i := 0; i < 2; i++ {
        c <- i
    }
}

func main() {
    c := make(chan int)
    go func() {
        for i := 0; i < 2; i++ {
            fmt.Println(<-c)
        }
    }()
    time.Sleep(0 * time.Second)
    sendNumbers(c)
}

In this code, the go routine I spawn should be able to receive 2 numbers before it returns. The sendNumbers() function I call next sends exactly 2 numbers to the channel c.

So, the expected output of the program is 2 lines: 0 and 1. However, what I'm getting when I run the code on the page, is just a single line containing 0.

Note the

time.Sleep(0 * time.Second) 

though that I deliberately added before calling sendNumbers(c). If I change it to

time.Sleep(1 * time.Second) 

The output becomes as expected:

0
1

So, I'm confused with what happens. Can someone explain what is going on? Shouldn't both sends and receives block regardless of how much time is passed before I call sendNumbers()?

  • 写回答

1条回答 默认 最新

  • doutan1857 2017-01-23 11:12
    关注

    In Go, the program exits as soon as the main function returns regardless of whether other goroutines are still running or not. If you want to make sure the main function does not exit prematurely, you need some synchronization mechanism. https://nathanleclaire.com/blog/2014/02/15/how-to-wait-for-all-goroutines-to-finish-executing-before-continuing/
    You don’t absolutely have to use synchronization primitives, you could also do it with channels only, arguably a more idiomatic way to do it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 plotBAPC画图出错
  • ¥30 关于#opencv#的问题:使用大疆无人机拍摄水稻田间图像,拼接成tif图片,用什么方法可以识别并框选出水稻作物行
  • ¥15 Python卡尔曼滤波融合
  • ¥20 iOS绕地区网络检测
  • ¥15 python验证码滑块图像识别
  • ¥15 根据背景及设计要求撰写设计报告
  • ¥20 能提供一下思路或者代码吗
  • ¥15 用twincat控制!
  • ¥15 请问一下这个运行结果是怎么来的
  • ¥15 单通道放大电路的工作原理