使用 goroutine 调用函数和将函数代码包装在 goroutine 中有区别吗?

Is there a difference between calling a function with a goroutine and wrapping a functions code in a goroutine?

我对 Golang 比较陌生,我正在努力了解 goroutine 的语义。 有区别吗:

func someFunc() {
    for {
        //some code handled by a persistent connection
    }
}

go someFunc()

func someFunc() {
    go func() {
        for {
            //some code handled by a persistent connection
        }
    }()
}

问题在于你想传达什么。通常,函数应该表示与该行为的操作模式无关的行为。如果有一天您的代码由于某些业务问题而变得全部异步,那么它不应该需要触及 someFunc.

中的任何代码

出于这个原因,我更喜欢前者而不是后者,但最终两者都会产生一个 goroutine 并在该线程上执行代码。前者的优点是 运行ning someFunc 同步成为可能。


还有其他一些小差异。 someFunc 的第一个定义是 运行ning 直到它完成它的行为。假设在 someFunc 期间采用了 long-运行ning expensiveAction,这样定义就变成了:

func someFunc() {
    ok := expensiveAction()
    if !ok {
        panic("Something bad happened")
    }
}

func someFunc() {
    go func() {
        ok := expensiveAction()
        if !ok {
            panic("Something bad happened")
        }
    }()
}

someFunc 的第一个定义在调用时将 运行 直到 expensiveAction 完成。第二个定义将定义匿名函数,启动 goroutine 并安排其执行,然后立即退出。这可能会使性能测试更加困难,甚至会产生细微的时序错误。