Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Go decide when to context switch between goroutines?

I am curious as to how the Go language schedules goroutines. Does it switch only during channel requests and I/O or does it have a periodic coroutine switching loop?

like image 479
abc def foo bar Avatar asked Aug 31 '13 07:08

abc def foo bar


People also ask

How does Go routine work?

Goroutines are functions or methods that run concurrently with other functions or methods. Goroutines can be thought of as lightweight threads. The cost of creating a Goroutine is tiny when compared to a thread. Hence it's common for Go applications to have thousands of Goroutines running concurrently.

When should we use Goroutines?

Goroutines are useful when you want to do multiple things simultaneously. For example, if you have ten things you want to do at the same time, you can do each one on a separate goroutine, and wait for all of them to finish.

How are Goroutines scheduled?

Goroutines are cooperatively scheduled, rather than relying on the kernel to manage their time sharing. The switch between goroutines only happens at well defined points, when an explicit call is made to the Go runtime scheduler. The compiler knows the registers which are in /use and saves them automatically.

Are Goroutines concurrent?

Golang provides goroutines to support concurrency in Go. A goroutine is a function that executes simultaneously with other goroutines in a program and are lightweight threads managed by Go.


1 Answers

Go does not have a preemptive scheduler yet, but one is planned for 1.2. So no, Go will not switch context during CPU-only calculations, only during I/O (reading from memory is also considered I/O if it isn't in a register already). You can read some discussion about it in Issue 543 - preemptive scheduling.

like image 174
Emil Vikström Avatar answered Sep 22 '22 10:09

Emil Vikström