In Go, a goroutine is a lightweight thread managed by the Go runtime. It’s different from a thread in several ways:
- Goroutines are multiplexed onto a smaller number of OS threads, allowing efficient use of system resources.
- Goroutines have a smaller stack size than threads, which reduces memory usage and allows for many more goroutines to be created.
- Goroutines are managed by the Go runtime, which handles scheduling, synchronization, and garbage collection, making it easier to write concurrent code.
- Goroutines are cheaper to create and destroy than threads, which makes it practical to use them for tasks that would be too expensive to perform with threads.
To create a goroutine, you simply add the keyword go in front of a function call:
func main() {
go myFunc() // start a new goroutine
}
func myFunc() {
// do something
}
In this example, myFunc() is executed concurrently in a new goroutine. The main() function continues to execute concurrently with myFunc().