你能检测出给定数量的 goroutine 将创建多少个线程吗?
我知道 goroutine 被复用到多个操作系统线程上,因此如果一个 goroutine 发生阻塞,例如在等待 I/O 时,其他 goroutine 会继续运行。但是,如果我要创建 n 个 goroutine,有没有办法提前知道我会生成多少个线程?
例如,如果我们调用下面的函数,我们是否知道将为 n 个 goroutine 创建多少(或最大数量)系统线程:
type Vector []float64
// Apply the operation to n elements of v starting at i.
func (v Vector) DoSome(i, n int, u Vector, c chan int) {
for ; i < n; i++ {
v[i] += u.Op(v[i])
}
c <- 1; // signal that this piece is done
}
I understand that goroutines are multiplexed onto multiple OS threads, so if one should block, such as while waiting for I/O, others continue to run. But is there any way to know ahead of time how many threads I would spawn if I was to create n goroutines?
For example, if we call the function below would we know how many (or the maximum number of) system threads would be created for n goroutines:
type Vector []float64
// Apply the operation to n elements of v starting at i.
func (v Vector) DoSome(i, n int, u Vector, c chan int) {
for ; i < n; i++ {
v[i] += u.Op(v[i])
}
c <- 1; // signal that this piece is done
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
每个 goroutine 一次最多可以使用一个线程。它是否使用线程取决于它正在做什么。 GOMAXPROCS 的值决定了自由运行的 Go 代码可以使用的线程数 - 换句话说,就是最大并行度。
然而,当 goroutine 在系统调用或调用 C 时直接阻塞时,即使 GOMAXPROCS=1 也可以使用更多线程。
以下操作不会导致 goroutine 在阻塞时使用线程:
这意味着,例如,如果您有许多 goroutine打开 /dev/ttyxx 并在读取时阻塞,您将为每个文件使用一个线程。如果您正在执行大量进程并等待它们退出,情况也是如此。
Each goroutine can use a maximum of one thread at a time. Whether it uses a thread or not depends on what it's doing. The value of GOMAXPROCS determines the number of threads that can be used by freely running Go code - in other words, the maximum level of parallelism.
However more threads can be used, even with GOMAXPROCS=1, when goroutines block directly on system calls or calls into C.
The following operations do not cause the goroutine to use a thread when they block:
This means, for example, that if you have many goroutines that open /dev/ttyxx and block on read, you'll be using a thread for each one. Same goes if you're execing a load of processes and waiting for them to exit.
根据 Pike 的围棋课程 PDF 幻灯片(第 3 天):
基于这篇博文,看起来设置环境变量 GOMAXPROCS 可以让您固定线程数。但是,如果您不指定此值,我不确定如何获取运行时将管理的默认线程数。
这篇博文似乎暗示如果您不设置环境变量,运行时将仅使用一个核心(大概是因为它仅使用一个进程。)
According to Pike's Go Course PDF slides (Day 3):
Based on this blog post, too, it would seem setting the environment variable
GOMAXPROCS
lets you fix the number of threads. I'm not sure how to get the default number of threads the runtime will manage if you do not specify this value, however.This blog post seems to imply that if you do not set the environment variable the runtime will only utilize one core (presumably because it is only using one process.)
目前,gccgo 将为每个 goroutine 创建一个线程。
6g不知道。
Currently, gccgo will create one thread per goroutine.
I don't know about 6g.