Golang Series
Hello GoLang: https://blog.yexca.net/archives/154
GoLang (var and const): https://blog.yexca.net/archives/155
GoLang (func): https://blog.yexca.net/archives/156
GoLang (slice and map): https://blog.yexca.net/archives/160
GoLang (OOP): https://blog.yexca.net/archives/162
GoLang (reflect): https://blog.yexca.net/archives/204
GoLang (struct tag): https://blog.yexca.net/archives/205
GoLang (goroutine): This Article
GoLang (channel): https://blog.yexca.net/archives/207
Process -> Thread -> Coroutine
A coroutine is a “lightweight thread.” You can easily spawn tens of thousands of them without exhausting system resources. Multiple coroutines share the resources allocated to their parent thread.
Go has native support for coroutines, which are called goroutines. Concurrency in Go is achieved through goroutines and channels.
Creating a Goroutine
Use the go keyword to start a goroutine.
| |
Using Anonymous Functions
You can also use anonymous functions with goroutines.
| |
Anonymous functions can take parameters and return values. However, to get a return value from a goroutine, you need to use a channel. The example below shows only parameters:
| |
Exiting
When the main goroutine exits, all other worker goroutines are automatically terminated.
You can also use runtime.Goexit() to immediately stop the current goroutine (any defer statements will still execute).
| |