Member-only story
Easy to Follow Engineering Tutorials
Golang Concurrency — Go Routines and Channels
A really simple introduction to Go Routines and Channels
Okay so…first off I’d like to apologize to my followers for not posting in months :’) I’ve been uhh…busy 😬 I’ll try to make up for it with better and more concise content though :) Hope you guys have all been well!
In today’s article we’ll be looking at the simplest example I can think of to illustrate what Go Routines and Channels are all about.
Go Routines are basically (from educative.io):
a lightweight execution thread in the Go programming language and a function that executes concurrently with the rest of the program. Goroutines are incredibly cheap when compared to traditional threads as the overhead of creating a goroutine is very low.
Let’s come up with the simplest example to illustrate this.
When we run this on Go Playground, here’s what we’ll get:
We can see that “Hello” and “World” gets printed consecutively but “Reine” doesn’t get printed at all.
The reason for this is because with our go
keyword, it spins off another thread (go routine) and it hasn’t had time to execute before the main program exits and finishes. Let us add in a sleep function to the main thread and see what happens.
Output:
We can see that Reine
now prints out — this is because there’s time for myFunc to execute now before the main() program exits.
Okay so that’s basically what Go Routines are all about. Now let’s move on to Channels.
In Golang, Channels are basically (from educative.io):