Concurrency & Parallelism in Golang
Ankit Malik
Engineering @Jiocinema | Go | Node.js | PHP | AWS | Azure | GCP | Serverless | Managed Cloud | REST | GraphQL
- How Concurrency is managed in Golang?
- Does concurrency mean parallelism?
- How does parallelism work in Golang?
I used to have these questions when I started working on Golang. I want to do this thing here and there.
Firstly We need to understand, what are Concurrency and Parallelism?
Concurrency:
Concurrency is doing multiple tasks at the same time. It means we are doing multiple tasks at the same time on 1 processor. If a thread is blocked then it will be swapped by another thread.
Parallelism:
Parallelism means doing the task parallelly. It means we are doing the tasks on multiple processors at the same time.
For multiprocessing, Golang has a feature called Goroutines. Goroutines are really simple and easy to implement. You need to add go before a function calling to call it as a goroutine.
Without goroutine example: simple example
With goroutine example: goroutine example
Above, we can see how goroutine is written.
Now, let us understand how parallelism and concurrency are implemented in Golang.
When we run goroutines, all goroutines are managed in a single processor, and all these goroutines are managed by go-runtime instead of OS kernel. Due to this reason, goroutines are independent of hardware.
Go runtime executes all these goroutines in a concurrent mode which means that all goroutines are managed by 1 process of Golang.
If we want them to run in multiprocessor mode then we can set the environment variable GOMAXPROCS parameter of Golang to execute goroutines on multiple processors. We can also set it programmatically.
After go-1.5, by default GOMAXPROCS is set to the number of processors. It clearly signifies that Golang has a great combination of parallelism with concurrency.