英文:
Does runtime.LockOSThread allow child goroutines to run in same OS thread?
问题
我了解在Go语言中,runtime.LockOSThread()
会将一个goroutine绑定到一个操作系统线程,并且不允许其他goroutine在该线程上执行。对于子goroutine也是如此吗?
例如:
runtime.LockOSThread()
go func() {
go func() {
// 做一些事情
}()
// 做一些事情
}()
这两个goroutine是否在同一个独占的操作系统线程上执行,还是只有第一个goroutine在执行?
英文:
I understand that in Go, runtime.LockOSThread()
will bind a goroutine to one OS thread and not allow other goroutines to execute in that thread.
Is this also true for child goroutines?
For example:
runtime.LockOSThread()
go func() {
go func() {
// Do something
}()
// Do something
}()
Do both of these goroutines execute in a single and exclusive OS thread or only the first one?
答案1
得分: 7
runtime.LockOSThread
的文档中写道:
> LockOSThread将调用的goroutine与其当前的操作系统线程绑定。直到调用的goroutine退出或调用UnlockOSThread之前,它将始终在该线程中执行,没有其他goroutine可以。
<sup>(我强调)</sup>
这意味着,如果Go的某个实现按照你的要求执行,那就是有错误的。
为了澄清:如果一个goroutine已经保留了一个线程,并且另一个goroutine在同一个线程上执行;那就是错误的。
英文:
The documentation for runtime.LockOSThread
says:
> LockOSThread wires the calling goroutine to its current operating system thread. Until the calling goroutine exits or calls UnlockOSThread, it will always execute in that thread, and no other goroutine can.
<sup>(emphasis mine)</sup>
This means that if a certain implementation of Go did what you're asking, it would be faulty.
To clarify: if a goroutine had reserved a thread and another goroutine executed on that same thread; that's what would be wrong.
答案2
得分: 6
我们可以使用pthread.h
的pthread_self
函数来检查它:
package main
// #include <pthread.h>
import "C"
import (
"fmt"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
ch1 := make(chan bool)
ch2 := make(chan bool)
fmt.Println("main", C.pthread_self())
go func() {
runtime.LockOSThread()
fmt.Println("locked", C.pthread_self())
go func() {
fmt.Println("locked child", C.pthread_self())
ch1 <- true
}()
ch2 <- true
}()
<-ch1
<-ch2
}
在我的机器上,它打印出类似以下的内容,main
和locked
有时相同,有时不同:
main 139711253194560
locked 139711219787520
locked child 139711236572928
编辑 我忘记了GOMAXPROCS。现在添加了,结果现在是变化的。
英文:
We can check it using pthread.h's pthread_self
:
package main
// #include <pthread.h>
import "C"
import (
"fmt"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
ch1 := make(chan bool)
ch2 := make(chan bool)
fmt.Println("main", C.pthread_self())
go func() {
runtime.LockOSThread()
fmt.Println("locked", C.pthread_self())
go func() {
fmt.Println("locked child", C.pthread_self())
ch1 <- true
}()
ch2 <- true
}()
<-ch1
<-ch2
}
On my machine it prints something like this, main
and locked
always being sometimes the same, but sometimes different:
main 139711253194560
locked 139711219787520
locked child 139711236572928
EDIT I forgot about GOMAXPROCS. Added, the results are varying now.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论