Search code examples
functiongoconcurrencygoroutine

Blocking Behaviour of GoRoutines in Golang


Given the following pseudo-code:

func main() {
  go runFuncOne()
}

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

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

Would runFuncTwo only be blocking to runFuncOne (the calling goroutine) or would runFuncTwo also block main() as it is not itself running as a goroutine?

My assumption is that main() will open a thread within which runFuncOne() and runFuncTwo() will then operate. Any work performed within runFuncTwo() will then only block this instance of runFuncOne()?


Solution

  • runFuncTwo blocks runFuncOne only, as both are running in a separate Go routine.

    Note though that main() will therefore continue and exit, causing the program to exit. To avoid this and all runFuncTwo to complete, you should use a sync.WaitGroup.