【英文】Go语言并发下的runtime包

Introduction

Notes on the runtime package in concurrent Go programming

Yielding CPU Time Slice

  • Whenever a goroutine executes runtime.Gosched(), it immediately yields its current time slice to allow other goroutines to execute.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package main

import "runtime"

func task() {
...
}

func main() {
go task()
for i := 0; i < 3; i++ {
runtime.Gosched()
}
}

Exiting Current Goroutine

  • Whenever a goroutine executes runtime.Goexit(), it immediately exits the current goroutine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package main

import "runtime"

func task() {
for i := 0; i < 3; i++ {
...
if i == 2 {
runtime.Goexit()
}
}
}

func main() {
go task()
}

Checking Number of CPU Cores in the Host

1
2
3
4
5
import "runtime"

func main() {
runtime.NumCPU()
}

Specifying the Number of CPU Cores to Use

  • go1.5 and earlier versions default to using 1 core, while go1.5 and later versions default to using the maximum number of cores in the host.

<num>: The maximum number of cores the Go program is allowed to use.

1
2
3
4
5
import "runtime"

func main() {
runtime.GOMAXPROCS(<num>)
}

Conclusion

References

哔哩哔哩——郭宏志-老郭