英文:
Go ignores GOMAXPROCS
问题
我正在尝试在主线程中同时运行一个无限循环和goroutine(go版本go1.4.1 darwin/amd64),但无法使其正常工作。如果我理解正确,如果我指定了GOMAXPROCS,go应该将goroutine调度到其他线程,但它并没有这样做。即使我在主函数中显式地写上LockOSThread()
,我仍然看不到输出。如何让go在单独的操作系统线程中运行goroutine?
package main
import(
"fmt"
"time"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU() * 8)
go func() {
for {
time.Sleep(1 * time.Second)
fmt.Println("From routine")
}
}()
for {}
}
英文:
I'm trying to run a goroutine (go version go1.4.1 darwin/amd64) simultaneously with endless loop in main thread and I can't make it works. If I understood correctly go should schedule a goroutine to other threads if I specify GOMAXPROCS but it won't. Even if I write explicitly LockOSThread()
in main I still can see no output. How to make go to run goroutine in separate os thread?
package main
import(
"fmt"
"time"
"runtime"
)
func main() {
runtime.GOMAXPROCS(runtime.NumCPU() * 8)
go func() {
for {
time.Sleep(1 * time.Second)
fmt.Println("From routine")
}
}()
for {}
}
答案1
得分: 3
问题在于当你进入for{}
循环时,新的goroutine尚未创建(因此无法调度)。调度器只能在goroutine被阻塞或调用另一个函数时工作,所以在一个封闭的循环中,调度器无法进行调度。
在for{}
之前添加time.Sleep(time.Millisecond)
,它就会起作用。
然而,我不知道你是否只是出于好玩而这样做,但如果你想要永远等待(或直到其他goroutine被死锁或死亡)而goroutine工作,最好使用select{}
,它会阻塞而不浪费CPU周期。
英文:
The problem is that the new goroutine is not yet created (so it cannot be scheluded) when you enter for{}
. The scheduler can only work then a goroutine is blocked or calls another function, so in a closed loop the scheduler cannot schedule.
Add a time.Sleep(time.Millisecond) before the for{}
and it will work.
However, I don't know if you are doing this just for fun, but if you want to wait forever (or until the other gorounties are dead-locked or die) while the goroutines work, it is much better to use select{}
that will block without wasting CPU cycles.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论