What is a goroutine ?
Keyword go is use to run a normal functon , they called it a goroutine.
package main
import "fmt"
func main() {
go fmt.Println("1") // a goroutine
fmt.Println("2")
}
[output]
2
Program exited.
the main program exist without waiting for the running goroutines :
go fmt.Println("1")
- Goroutines are not threads. They're a bit like threads, but they're much cheaper.Goroutines are lightweight and low memory consumption compared to threads. They have a very small footprint (use little memory and resources): they are created with a 4K memory stack-space on the heap. Because they are cheap to create, a great number of them can be started on the fly if necessary (in the order of 100 thousands in the same address space).
- Goroutine's stack management is automatic. Goroutines use a segmented stack for dynamically growing (or shrinking) their memory-usage , the stacks are not managed by the garbage collector, instead they are freed directly when the goroutine exits.
- Goroutines are multiplexed onto OS threads as required. Goroutines can run across multiple operating system threads. They can also run within threads, letting you handle myriad tasks with a relatively small memory footprint.
- When a goroutine blocks, that thread blocks but no other goroutine blocks.
It is easy to use goroutines to make a non blocking web server , with clean and readable synchronous code , avoid callback hell code style in javascript.
Althought goroutines allow you to execute tasks in parallel , it won't reveal its real concurrent power without introducing channels. Without channels , goroutines are just like working in a "isolated" spaces without communicating - it's like the superman lost the power to fly.
Further reference:
- THE WAY TO GO - A Thorough Introduction to the Go Programming Language [ By IVO BALBAERT ]