Ever wondered the reason behind Golang's growth in recent times ? Well, besides being fast and simple to learn Golang has an inbuilt support for concurrency i.e. goroutines and channels. One can question the need for concurrency in the presence of parallelism. Imagine that you are managing a website with just one core and you have a lot of processing to complete. Which method would you use? Concurrency is the answer, and not parallelism because parallelism's full potential is unleashed with multicore systems. On a single core, many threads can be running, switching among themselves and emulating parallelism. Parallelism loses out to concurrency when resources are scarce.
Limitations of threads
- Absence of easy inter-threads communication medium causes latency. Threads communicate via sharing of memory causes concurrent access to memory which leads to data race condition and the result can be un deterministic.
- Generally few thousands thread can be created. Hardware dependent.
- Threads manipulations are expensive operations. They require switch to kernel return back, save and restore stack and so on.
How goroutines overcome threads ?
- Goroutines can easily communicate with each other using channels and that too without sharing of memory, so low latency.
- Goroutines are multiplexed to fewer number of OS threads. Stack size of go-routines starts from 2kb and can grow and shrink. On linux, Os threads are of size 8 MB while Java's JVM threads are 1MB (default value) stack per thread.
- So on 1GB of RAM system , JVM can have around ~1k threads while we can have ~0.5 million goroutines. Goroutines have low CPU overheads with 3 instructions per function call. Context switching between go routines are cheaper than thread context switching.
Goroutines provide an edge for Golang over other languages. Due to its incredibly simple concurrency capability, Go Lang appears to be a language for the future. Language has already received a lot of attention, especially in the cloud computing community. Firms, such as Uber, BBC, Novartis, Sound Cloud are using Golang .
Did you find this article valuable?
Support Ayush Raj by becoming a sponsor. Any amount is appreciated!