NOTE
2.14 goroutine
Goroutines are user-level execution units implemented by Go. These notes connect them with processes and threads and record their creation and use.
This is a historical learning note and may contain outdated or incomplete understanding.
1. What Is a goroutine
- Programs, processes, and threads.md (related note is not yet published)
- A user thread implemented by the Go language
- Compared with threads, goroutines have:
- Creation, destruction, and switching: all completed in user space without entering the kernel
- Memory usage: the default stack size is 2K and can dynamically grow and shrink
2. goroutine Usage
2.1. Create a Goroutine
func TestGoroutine1(t *testing.T) {
go func(x, y, z int) {
time.Sleep(time.Second * 1)
fmt.Println(x + y + z)
}(1, 2, 3)
time.Sleep(time.Minute * 5)
}
go f(x, y, z)starts a new goroutine to run the functionf(x, y, z)- The function
fand the values of variablesx,y, andzare evaluated in the original goroutine; only the execution of functionfhappens in the new goroutine - The new goroutine creates a new stack
- The function
2.2. Goroutine Pool
3. goroutine Implementation
func TestGoroutine1(t *testing.T) {
go func(x, y, z int) {
time.Sleep(time.Second * 1)
fmt.Println(x + y + z)
}(1, 2, 3)
time.Sleep(time.Minute * 5)
}
go tool compile -SGoroutine function callgo f(1, 2, 3):
0x0024 00036 (goroutine1_test.go:10) PCDATA $0, $0
0x0024 00036 (goroutine1_test.go:10) PCDATA $1, $0
0x0024 00036 (goroutine1_test.go:10) MOVL $24, (SP)
0x002b 00043 (goroutine1_test.go:10) PCDATA $0, $1
0x002b 00043 (goroutine1_test.go:10) LEAQ "".TestGoroutine1.func1·f(SB), AX
0x0032 00050 (goroutine1_test.go:10) PCDATA $0, $0
0x0032 00050 (goroutine1_test.go:10) MOVQ AX, 8(SP)
0x0037 00055 (goroutine1_test.go:10) MOVQ $1, 16(SP)
0x0040 00064 (goroutine1_test.go:10) MOVQ $2, 24(SP)
0x0049 00073 (goroutine1_test.go:10) MOVQ $3, 32(SP)
0x0052 00082 (goroutine1_test.go:10) CALL runtime.newproc(SB)
It can be seen that it calls CALL runtime.newproc(SB).
That is, go f(args) is equivalent to runtime.newproc(size, f, args).
4. goroutine Scheduling
5. References
Drag to pan, scroll to zoom, and click a node to expand or collapse it. Large maps start with deeper levels collapsed; click nodes to expand them.
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub