Goroutines: Explained Further
Let's get to know what is happening behind the scenes of a goroutine.
So far, you already know that the go statement runs a function in a separate thread of execution. The simplicity of the go
command to create concurrent processes is what sets the Golang apart from other languages. Previously, developers used threads to implement concurrency in C++/Java which made it a bit complicated. But with Golang, you simply type go function/method
and the program creates a goroutine which will execute concurrently and immediately return to the next line of the code in the parent routine. In doing so, the program will ignore any return values from the goroutine. This ease with which concurrency can be implemented using Go has made it popular in the concurrent programming world.
The Fork-Join Model
Go uses the idea of the fork-join model of concurrency behind goroutines. The fork-join model essentially implies that a child thread/process splits from its parent thread/process to run concurrently with the parent process. After completing its execution, the child process merges back into the parent process. The point where it joins back is called the join point. Goroutines work in a similar fashion. Sometimes you won’t have a join point in your program, for example, in cases where goroutines only print onto the console and exit. On the other hand, if you’ll have a join point, you’ll have to synchronize your goroutine with the rest of the program.
Here is an illustration to help you better understand the fork-join model:
Get hands-on with 1400+ tech skills courses.