NOTE

2.14 goroutine

What a goroutine is, how to create one, how go f(args) maps to runtime.newproc, goroutine pools, and GMP scheduling.

GoCreated Updated 1 min readhistorical

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 function f(x, y, z)
    • The function f and the values of variables x, y, and z are evaluated in the original goroutine; only the execution of function f happens in the new goroutine
    • The new goroutine creates a new stack

2.2. Goroutine Pool

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 -S Goroutine function call go 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

GMP.md

5. References

Discussion

Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub