Why GoRoutines are better than Threads?

wisdom uchewisdom uche
2 min read

yea!

In the concurrency war, goroutine has defeated thread with the use of channels and is less expensive.

Image edited on photopeak

Introduction

Ever wondered about 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

  1. The absence of an easy inter-thread communication medium causes latency. Threads communicate via sharing of memory causing concurrent access to memory which leads to data race conditions and the result can be un-deterministic.

  2. Generally, a few thousands thread can be created. Hardware dependent.

  3. Threads manipulations are expensive operations. They require a switch to kernel return back, save and restore stack and so on.

How do goroutines overcome threads?

  1. Goroutines can easily communicate with each other using channels and that too without sharing of memory, so low latency.

  2. Goroutines are multiplexed to fewer OS threads. The 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.

  3. Goroutines have low CPU overheads with 3 instructions per function call. Context switching between go routines is cheaper than thread context switching.

Conclusion

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, and Sound Cloud are using Golang.

0
Subscribe to my newsletter

Read articles from wisdom uche directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

wisdom uche
wisdom uche

Backend Engineer, Devops-gee Author/writer