Golang is one of the sought-after languages for anyone looking for excellent performance without the accompanying headache of deciphering complex code. Created by the original developers of the C language, Golang is a modern language that solves modern problems with modern solutions. One notable feature that maximizes efficiency in Golang is the integration of go-routines, a powerful mechanism for handling concurrency. To fully harness the benefits of go-routines, it's crucial to understand how they work and the common patterns employed when dealing with the same.

Control Flow:

To better understand asynchronous control flow, let's understand how ‘synchronous control flow’ or ‘normal sequential code’ works. In the animation below you can observe the main function on the left side of the frame. We have a function called getFromAPI() defined on the right side of the frame. This function is then called from the main function.

<aside> 💡 Try clicking on the EXECUTE CODE button to reveal the flow of the main execution thread.

</aside>

https://animonic.xyz/frag/goroutine_1

As you might have observed, the main execution jumps to execute the function before it proceeds with the main function. If it's a long-running function the main thread will have to wait for the function to complete or if there are a bunch of things that need to be done, they will all have to be executed sequentially (Without concurrency to be precise).

<aside> 💡 Click on the “MAKE GOROUTINE CALL” button to convert the sync call to a go-routine call.

</aside>

On making the function call a go-routine observe how the return button fades, as the usual return won’t work (the same is handled in other ways, which is explained later). The function call is prefixed with the go keyword. This is to indicate to the compiler that we want to dispatch a go-routine to execute the function remotely and independently in its own world, of sorts.

<aside> 💡 Click on “EXECUTE CODE” again to see go-routines work in action.

</aside>

<aside> ⚠️ But there’s an error! The go-routines are all killed if the main function exits.

</aside>

<aside> 💡 Let’s wait for our go-routine by clicking on the “ADD SLEEP IN MAIN” button. And then click on “EXECUTE CODE” and observe that all the processes exit normally.

</aside>

🤔 So what is a go-routine exactly?

A go-routine is a special way of running functions in Go (Golang) that allows them to work concurrently. The scheduler takes care of actually scheduling them and making use of the limited OS threads.

⚠️ But there are a few problems!

  1. Remember, how the returns don’t work anymore, because we have decoupled the context which calls the function, and the actual execution of the function.
  2. And you might have also observed the alert that popped up in the simulation that if the main function finishes execution before the go-routines, the go-routines are killed straight away!

💭 If only go-routines could communicate back!