Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are goroutines much cheaper than threads in other languages?

Tags:

go

goroutine

In his talk - https://blog.golang.org/concurrency-is-not-parallelism, Rob Pike says that go routines are similar to threads but much much cheaper. Can someone explain why?

like image 488
aamir Avatar asked Jan 28 '17 04:01

aamir


People also ask

Why are Goroutines better than threads?

Goroutines have easy communication medium known as channel. Thread does not have easy communication medium. Due to the presence of channel one goroutine can communicate with other goroutine with low latency.

Are Goroutines expensive?

In Go, goroutines are cheap to create and efficient to schedule. The Go runtime has been written for programs with tens of thousands of goroutines as the norm, hundreds of thousands are not unexpected. But goroutines do have a finite cost in terms of memory footprint; you cannot create an infinite number of them.

Are Goroutines just threads?

Goroutine is a lightweight thread in Golang. All programs executed by Golang run on the Goroutine. That is, the main function is also executed on the Goroutine. In other words, every program in Golang must have a least one Goroutine.

Why Goroutines are faster?

In Golang, Goroutines are used to achieve concurrency. They are lightweight threads managed by the Go runtime. Goroutines make it possible to create concurrent programs that can execute tasks faster than a regular sequential program would.


1 Answers

See "How goroutines work".
They are cheaper in:

  • memory consumption:
    A thread starts with a large memory as opposed to a few Kb.
  • Setup and teardown costs
    (That is why you have to maintain a pool of thread)
  • Switching costs
    Threads are scheduled preemptively, and during a thread switch, the scheduler needs to save/restore ALL registers.
    As opposed to Go where the the runtime manages the goroutines throughout from creation to scheduling to teardown. And the number of registers to save is lower.

Plus, as mentioned in "Go’s march to low-latency GC", a GC is easier to implement when the runtime is in charge of managing goroutines:

Since the introduction of its concurrent GC in Go 1.5, the runtime has kept track of whether a goroutine has executed since its stack was last scanned. The mark termination phase would check each goroutine to see whether it had recently run, and would rescan the few that had.

In Go 1.7, the runtime maintains a separate short list of such goroutines. This removes the need to look through the entire list of goroutines while user code is paused, and greatly reduces the number of memory accesses that can trigger the kernel’s NUMA-related memory migration code.

like image 82
VonC Avatar answered Nov 15 '22 04:11

VonC