go - 为什么 goroutine 中的 fmt.Println 不打印一行?

标签 go

我有以下代码:

package main

import "net"
import "fmt"
import "bufio"

func main() {
    conn, _ := net.Dial("tcp", "irc.freenode.net:6667")

    reader := bufio.NewReader(conn)
    go func() {
        str, err := reader.ReadString('\n')
        if err != nil {
            // handle it
            fmt.Println(err)
        }
        fmt.Println(str)
    }()

}

如果我没有从 goroutine 中的缓冲区读取的代码,它会输出这样的消息,这是我期望发生的:

:zelazny.freenode.net NOTICE * :*** Looking up your hostname...

但是,将它放在 goroutine 中不会打印任何内容。

谁能解释为什么会这样?

最佳答案

您的程序将在 main() 函数完成时退出。这很可能在您的 goroutine 有时间运行并打印其输出之前发生。

一种选择是让主 goroutine block 从 channel 读取,并让 goroutine 在完成工作后写入 channel 。

关于go - 为什么 goroutine 中的 fmt.Println 不打印一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16228887/

相关文章:

go - AWS Lambda GoLang 处理程序 API

go - 多次运行相同的go程序会引发 panic : send on closed channel

go - CGO : Undefined symbols for architecture x86_64

javascript - 查找 PHP、Node 和 Golang 中两个数组之间的区别

pointers - 在 Go HTTP 处理程序中,为什么 ResponseWriter 是一个值,而 Request 是一个指针?

function - 函数可以在 Go 中实现接口(interface)吗

Golang 403 禁止错误

go - 一次检查golang中的所有数据键

mongodb - 如何使用GoLang在MongoDB中执行插入操作?

mongodb - TCP连接管理