douhanzhen8927 2013-07-28 04:04
浏览 35
已采纳

奇怪的例行行为

Please correct me if I am wrong. As long as I know, goroutine works roughly similar to threads. So If I spawn the same function with different parameters prefixing with go. It should work perfectly fine ?

package main

import "fmt"


func f(from string) {
    for i := 0; i < 3; i++ {
        fmt.Println(from, ":", i)
    }
}

func main() {
    go f("direct")
    go f("redirect")
    //var input string
    //fmt.Scanln(&input)

}

Actual Output:

rahul@g3ck0:~/programs/go$ go run goroutine.go 
rahul@g3ck0:~/programs/go$ 

I just get back prompt.

Expected output:

direct : 0
direct : 1
direct : 2
redirect : 0
redirect : 1
redirect : 2

Not necessarily in the same order.
Not able to understand this strange behaviour. Am I missing something ?

EDIT: Adding a Scan statement resolves it. But is there any better way of doing it ?

  • 写回答

2条回答 默认 最新

  • duanchijie2323 2013-07-28 04:13
    关注

    When main exits, the program terminates regardless of the state of other goroutines. You can test this by adding select{} at the end of your main function. This will cause main to never exit and you will see the other goroutines run.

    If you want your program to exit cleanly (without a deadlock) when both goroutines complete, you need to use something like a channel or sync.Waitgroup to coordinate main ending when everything is complete.

    Example using sync.Waitgroup:

    package main
    
    import (
        "fmt"
        "sync"
    )
    
    func f(from string, wg *sync.WaitGroup) {
        for i := 0; i < 3; i++ {
            fmt.Println(from, ":", i)
        }
    
        wg.Done()
    }
    
    func main() {
        wg := new(sync.WaitGroup)
        wg.Add(2)
    
        go f("direct", wg)
        go f("redirect", wg)
    
        wg.Wait()
    }
    

    Example using channels:

    package main
    
    import (
        "fmt"
    )
    
    func f(from string, ch chan<- bool) {
        for i := 0; i < 3; i++ {
            fmt.Println(from, ":", i)
        }
    
        ch <- true
    }
    
    func main() {
        ch := make(chan bool)
    
        go f("direct", ch)
        go f("redirect", ch)
    
        <-ch
        <-ch
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程