Golang 中 GoRoutines 的阻塞行为

Blocking Behaviour of GoRoutines in Golang

给定以下伪代码:

func main() {
  go runFuncOne()
}

func runFuncOne() bool {
  runFuncTwo() 
  return true
}

func runFuncTwo() bool {
  // Do some heavy work
  return true
}

runFuncTwo 只会阻塞 runFuncOne (调用 goroutine)或者 runFuncTwo 也会阻塞 main() 因为它本身不是 运行协程?

我的假设是 main() 将打开一个线程,然后 runFuncOne()runFuncTwo() 将在其中运行。在 runFuncTwo() 中执行的任何工作都只会阻止 runFuncOne()?

的这个实例

runFuncTwo 仅阻塞 runFuncOne,因为两者都 运行 在单独的 Go 例程中。

请注意,尽管 main() 将因此继续并退出,从而导致程序退出。为了避免这个和所有 runFuncTwo 完成,你应该使用 sync.WaitGroup.

The Go Programming Language Specification

Go statements

The function value and parameters are evaluated as usual in the calling goroutine, but unlike with a regular call, program execution does not wait for the invoked function to complete. Instead, the function begins executing independently in a new goroutine. When the function terminates, its goroutine also terminates. If the function has any return values, they are discarded when the function completes.

func main() {
  go runFuncOne()
}

main 将调用 runFuncOne() 作为 goroutine,然后立即退出程序,终止 runFuncOne() 而无需等待它完成。

func runFuncOne() bool {
  runFuncTwo() 
  return true
}

func runFuncTwo() bool {
  // Do some heavy work
  return true
}

runFuncOne()runFuncTwo() 进行函数调用,因此它将等待 runFuncTwo() 完成。

也可以使用频道进行同步:

package main

import (
    "fmt"
    "time"
)

func main() {
    var ch chan int = make(chan int)
    go runFuncOne(ch)
    fmt.Println("Waiting..")
    fmt.Println(<-ch)
}

func runFuncOne(ch chan int) {
    runFuncTwo(ch)
    ch <- 1
}

func runFuncTwo(ch chan int) bool {
    time.Sleep(1 * time.Second)
    fmt.Println("Done working..")
    return true
}

https://play.golang.org/p/h1S4TSdT0w

Return 如果您使用 go 例程调用它,runFuncOne 类型将不会产生影响。