Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do goroutines work? (or: goroutines and OS threads relation)

How can other goroutines keep executing whilst invoking a syscall? (when using GOMAXPROCS=1)
As far as I'm aware of, when invoking a syscall the thread gives up control until the syscall returns. How can Go achieve this concurrency without creating a system thread per blocking-on-syscall goroutine?

From the documentation:

Goroutines

They're called goroutines because the existing terms—threads, coroutines, processes, and so on—convey inaccurate connotations. A goroutine has a simple model: it is a function executing concurrently with other goroutines in the same address space. It is lightweight, costing little more than the allocation of stack space. And the stacks start small, so they are cheap, and grow by allocating (and freeing) heap storage as required.

Goroutines are multiplexed onto multiple OS threads so if one should block, such as while waiting for I/O, others continue to run. Their design hides many of the complexities of thread creation and management.

like image 283
omribahumi Avatar asked Jul 06 '14 19:07

omribahumi


People also ask

Do Goroutines use 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.

Are Goroutines the same as threads?

A thread is a lightweight process, or in other words, a thread is a unit which executes the code under the program. So every program has logic and a thread is responsible for executing this logic. Goroutines are managed by the go runtime. Operating system threads are managed by kernal.

What are Goroutines and how do they work?

GoRoutines are a Golang wrapper on top of threads and managed by Go runtime rather than the operating system. Go runtime has the responsibility to assign or withdraw memory resources from Goroutines. A Goroutine is much like a thread to accomplish multiple tasks, but consumes fewer resources than OS threads.

Do Goroutines use multiple threads?

At any time, at most only one thread is allowed to run per core. But scheduler can create more threads if required, but that rarely happens. If your program doesn't start any additional goroutines, it will naturally run in only one thread no matter how many cores you allow it to use.


1 Answers

If a goroutine is blocking, the runtime will start a new OS thread to handle the other goroutines until the blocking one stops blocking.

Reference : https://groups.google.com/forum/#!topic/golang-nuts/2IdA34yR8gQ

like image 100
OneOfOne Avatar answered Oct 02 '22 18:10

OneOfOne