Goroutines
Learn about Goroutines in Go.
What are goroutines
For most intents and purposes goroutines can be thought of as lightweight threads. They’re quick to start, initially use only 2kb of stack memory (which can grow or shrink). They’re managed by the Go runtime (rather than the operating system) and context switching between them is cheap. goroutines are built for concurrency and when run on multiple hardware threads they will also run in parallel.
It’s scary how efficient goroutines are and when combined with channels they could well be the best feature of Go. They’re everywhere in Go, but an extreme example of a good problem for goroutines could be a server managing lots of concurrent websocket connections. They need to be managed individually, but they’re mostly sitting idle (not using much CPU or memory). Creating a thread for each of them would cause problems once it gets to thousands of connections, while with goroutines hundreds of thousands are possible.
Running goroutines don’t stop a program from exiting
Go program exits when the main
function exits. Any goroutines running in the background quietly stop. The following program will exit without printing anything:
Get hands-on with 1400+ tech skills courses.