go 进程生成的 OS 线程数会不会减少?

Will the number of OS threads spawned by go process never decrease?

考虑一个系统上的 golang 程序 运行,GOMAXPROCS 值为 10。由于阻塞系统调用,OS 产生了 30 个以上的线程,导致 40 个 OS 线程附加到进程.

在所有被阻塞的系统调用 returns 之后,进程是否仍然有 40 个 OS 线程?如果是,那么我们是否可以得出结论,映射到 golang 进程的 OS 线程数量可以增长但永远不会下降?

是的,当前由于阻塞的 goroutines 而产生的线程不会停止。关于定期关闭空闲线程的讨论:runtime: let idle OS threads exit #14592

虽然有一种方法可以终止线程。如果您根据文档调用 runtime.LockOSThread() in a goroutine without calling its counterpart runtime.UnlockOSThread()

If the calling goroutine exits without unlocking the thread, the thread will be terminated.

您也可以使用(来源:runtime: terminate locked OS thread if its goroutine exits #20395):

syscall.Syscall(syscall.SYS_EXIT, 0, 0, 0)