Golang中常用的"runtime"和"runtime/debug"函数有哪些?
Golang中常用的"runtime"和"runtime/debug"函数有哪些? 我倾向于使用 debug.SetMaxStack() 和 runtime.Gosched()。
更多关于Golang中常用的"runtime"和"runtime/debug"函数有哪些?的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
在Go语言中,runtime和runtime/debug包提供了许多用于调试和运行时控制的函数。以下是一些常用函数及其示例:
runtime包常用函数:
-
runtime.Gosched():让出当前goroutine的处理器时间,允许其他goroutine运行。
package main import ( "fmt" "runtime" ) func main() { go func() { for i := 0; i < 3; i++ { fmt.Println("goroutine 1") } }() runtime.Gosched() // 让出时间片给上面的goroutine fmt.Println("main goroutine") } -
runtime.NumGoroutine():返回当前存在的goroutine数量。
fmt.Println("当前goroutine数:", runtime.NumGoroutine()) -
runtime.GOMAXPROCS():设置或查询可同时执行的最大CPU核心数。
fmt.Println("当前最大CPU数:", runtime.GOMAXPROCS(0)) runtime.GOMAXPROCS(4) // 设置为4个CPU核心 -
runtime.GC():触发一次垃圾回收。
runtime.GC()
runtime/debug包常用函数:
-
debug.SetMaxStack():设置单个goroutine可使用的最大栈内存(字节)。
package main import ( "runtime/debug" ) func main() { // 设置最大栈大小为64KB debug.SetMaxStack(64 * 1024) } -
debug.SetMaxThreads():设置程序最大系统线程数。
debug.SetMaxThreads(10000) -
debug.FreeOSMemory():强制释放内存给操作系统。
debug.FreeOSMemory() -
debug.PrintStack():打印当前goroutine的堆栈跟踪信息。
debug.PrintStack() -
debug.ReadGCStats():读取垃圾回收统计信息。
var stats debug.GCStats debug.ReadGCStats(&stats) fmt.Printf("GC次数: %d\n", stats.NumGC)
这些函数在性能调优、调试和资源控制场景中非常有用。例如,debug.SetMaxStack()可以防止goroutine栈溢出,runtime.Gosched()可用于协作式调度。

