multithreading - Go运行时使用的线程数

标签 multithreading go docker concurrency goroutine

Go 运行时(调度程序、垃圾收集器等)可以使用多少个线程?例如,如果 GOMAXPROCS10,那么运行时将使用多少内核线程?

编辑:

我正在阅读 the rationale在 Go 1.5 中将 GOMAXPROCS 更改为 runtime.NumCPU()。有一句话声称“由于运行时的并行性,尤其是垃圾收集器,单 goroutine 程序的性能可以通过提高 GOMAXPROCS 来提高。”

我真正的问题是:如果我有一个在具有 CPU 配额的 Docker 容器中运行的单 goroutine 程序,为了获得最佳性能,我需要的最少逻辑处理器数量是多少?

最佳答案

没有直接的相关性。您的应用使用的线程可能小于、等于或大于 10。

引用自 runtime 的包文档:

The GOMAXPROCS variable limits the number of operating system threads that can execute user-level Go code simultaneously. There is no limit to the number of threads that can be blocked in system calls on behalf of Go code; those do not count against the GOMAXPROCS limit. This package's GOMAXPROCS function queries and changes the limit.

因此,如果您的应用程序不启动任何新的 goroutine,线程数将少于 10。

如果您的应用程序启动了许多 goroutines (>10) 而没有阻塞(例如在系统调用中),则 10 个操作系统线程将同时执行您的 goroutines。

如果您的应用程序启动了许多 goroutine,其中许多 (>10) 在系统调用中被阻塞,则将产生超过 10 个操作系统线程(但最多只有 10 个将执行用户级 Go 代码)。

有关示例和详细信息,请参阅此问题:Why does it not create many threads when many goroutines are blocked in writing file in golang?

编辑(响应您的编辑):

我相信 GOMAXPROCS 的默认值是逻辑 CPU 的数量是有原因的:因为通常它提供最高的性能。你可以就此打住。一般来说,如果你只有 1 个 goroutine,并且你确定你的代码不会产生更多,GOMAXPROCS=1 就足够了,但你应该测试并且不要相信它。

关于multithreading - Go运行时使用的线程数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58006873/

相关文章:

go - 在 go lang bytes 包中找不到 NewBuffer([]bytes,int,int64) 方法

datetime - foo.Seconds()(类型为time.Duration)错误-无法将'd.Step.Seconds()'(类型为float64)用作time.Duration类型

ip-address - 为 docker 容器分配 IP 地址?

multithreading - 使用 Spring 批处理文件项阅读器进行多线程处理

c# - 从任务返回而不阻塞 UI 线程

objective-c - 锁定一个对象不被多个线程访问 - Objective-C

android - ListView 延迟加载图片组件的设计

unit-testing - 我如何在 Go 中编写使用 -short 标志的测试,它可以与 -benchmark 标志结合使用吗?

docker - Kubernetes中的Redis哨兵集群,哨兵无法到达redis master

java - 使Hazelcast Native Client与Hibernate 5.2.x一起使用