dongzongzhi6953 2018-05-10 23:28
浏览 47
已采纳

监听和服务Goroutine阻止主进程的执行,从未达到用于通信的以下选择状态

Still fully getting my head around goroutines and channels, so I might be doing something obviously wrong. I have a service that runs a websocket server and public route used to upgrade clients from https to wss. I am trying to attach some tear-down code for one of the routines, but the second go call seems to block the main function's execution. I reach Println 5 on the console on boot up. The rest of my program is happily working. I just can't kill it with a ctrl+C (nor does it do it's required tear down after a manual shut down).

Here's the relevant code (the complete main file minus the streamAddr var and the imports):

func main() {
    fmt.Println(1)
    flag.Parse()
    log.SetFlags(0)

    fmt.Println(2)
    interrupt := make(chan os.Signal, 1)
    signal.Notify(interrupt, os.Interrupt)

    fmt.Println(3)
    hub := socktools.NewHub()
    go hub.Run()

    fmt.Println(4)
    http.HandleFunc("/stream", func(w http.ResponseWriter, r *http.Request) {
        socktools.ServeWs(hub, w, r)
    })

    fmt.Println(5)
    go log.Fatal(http.ListenAndServe(*streamAddr, nil))

    fmt.Println(6)

    select {
    case <-interrupt:
        fmt.Println("Interrupt heard...")
        close(hub.KillChan)
        <-hub.KilledChan
        fmt.Println("Ending main function")
        return
   }
}

Why is go log.Fatal(http.ListenAndServe(*streamAddr, nil)) blocking? I thought that the go keyword instantly made it asynchronous? Am I using it wrong here?

  • 写回答

1条回答 默认 最新

  • doutao6653 2018-05-10 23:41
    关注

    You are essentially calling go log.Fatal(variable), so the async call is log.Fatal, but it has to know what variable is at that moment, so it first has to call http.ListenAndServe to see what it returns. But http.ListenAndServe blocks.

    You need to do:

    go func() {
        log.Fatal(http.ListenAndServe(*streamAddr, nil))
    }()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 求给定范围的全体素数p的(p-2)的连乘积
  • ¥15 VFP如何使用阿里TTS实现文字转语音?
  • ¥100 需要跳转番茄畅听app的adb命令
  • ¥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的方法去调试网页