在 Linux 上运行 Go(Golang)程序“卡住/卡死/卡顿”,原因很多,需要分情况排查。下面按常见原因 → 排查方法 → 解决办法给你一个实用清单。
先区分是:
可用:
top
htop
ps -ef | grep 你的程序
Go 最常见“卡住”原因。
表现
fatal error: all goroutines are asleep - deadlock!
常见原因
排查
go build -race
./你的程序
示例错误写法
ch := make(chan int)
ch <- 1 // 没人接收,卡死
解决
buffered channelsync.WaitGroup表现
top 里 goroutine 数巨大排查
go tool pprof
代码中加:
import _ "net/http/pprof"
然后:
go tool pprof http://localhost:6060/debug/pprof/goroutine
解决
go func()表现
dmesg 中有 OOMdmesg | grep -i oom
解决
free -h
ulimit -a
限制内存:
ulimit -v 512000
表现
排查
iostat
lsof -p 进程ID
strace -p 进程ID
解决
bufioexport GOMAXPROCS=核心数
查看:
nproc
如果你用了:
import "C"
排查
CGO_ENABLED=0 go build
你可以告诉我:
我可以直接帮你定位代码问题。