dongxie9448 2016-10-29 03:12
浏览 126

Golang例程提前终止

I just started using go and wrote my first program but the output is not as expected. I have writtern a async routine addUrl which adds url to channel 5000 times and consumeUrl removes from the channel and prints it. The routine runs only 9 time. Why is it? Below is the code and output

package main

import "fmt"
import "time"

var urlCount = 0

func main(){

    urlHolder := make(chan string,5000)

    fmt.Printf("Starting program")

    go addUrls(urlHolder)

    time.Sleep(time.Millisecond * 100)
    go consumeUrls(urlHolder)

    fmt.Printf("Done")

}

func addUrls(urlHolder chan string){
    var myurl string = "https://example.com/"

    for i:=0; i<5000 ; i++ {
        urlHolder<-myurl
        fmt.Printf(" %d url added 
",i)
        time.Sleep(time.Millisecond * 10)
    }

}

func consumeUrls(urlHolder chan string) {
    urlCount++
    urlsConsumed := <- urlHolder
    fmt.Printf("Pulled url %d",urlCount," ",urlsConsumed,"
")
    time.Sleep(time.Millisecond * 20)
}  

The output is

Starting program
 0 url added 
 1 url added 
 2 url added 
 3 url added 
 4 url added 
 5 url added 
 6 url added 
 7 url added 
 8 url added 
Done

Why is it terminating at 8 when loop is 5000?

  • 写回答

2条回答 默认 最新

  • dongzen7263 2016-10-29 05:34
    关注

    Actually The problem was like Nipun said, the main got terminated early.

    评论

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制