可能发生的情况是for循环不断增加新的goroutines到可用的goroutine列表中,但由于整个过程只在一个OS线程中运行,Go调度程序从未得到实际上安排了一个不同的goroutine,并且不停地运行那个for循环,而没有运行任何你产生的goroutine。试试这个:

  package main 

importos

func main(){
for {
go func(){os.Exit(0)}()
func(){}()
}
}

如果您在Go Playground上运行它,它应该可以工作(事实上,这里有一个链接)。



好的,上面的代码工作,而你的不应该很神秘。这样做的原因是Go调度程序实际上是非抢占式的。这意味着,除非给定的goroutine自愿决定让调度程序选择运行其他方法,否则其他方法都不会运行。

 func(){}() os.Exit 


 runtime.Gosched()

I have a research program with very simple algorithm. When success is coming goroutine should be close (end) via os.Exit(0). I'm wait one day, two day.... What? :)

Here is the simple code

package main

import "os"

func main() {
    for {
        go func() { os.Exit(0) }()
    }
}

And my questions:

  1. Why os.Exit doesn't terminate the goroutine?
  2. What is correct way to terminate (stop) goroutine execute?
os.Exit

What probably happened was that the for loop kept adding new goroutines to the list of available goroutines, but since the entire process was only running in one OS thread, the Go scheduler never got around to actually scheduling a different goroutine, and just kept running that for loop without ever running any of the goroutines you'd spawned. Try this instead:

package main

import "os"

func main() {
    for {
        go func() { os.Exit(0) }()
        func() {}()
    }
}

If you run it on the Go Playground, it should work (in fact, here's a link).

OK, the fact that the above code works while yours doesn't should be pretty mysterious. The reason this works is that the Go scheduler is actually non-preempting. What that means is that unless a given goroutine voluntarily decides to give the scheduler the option to run something else, nothing else will run.

func() {}()os.Exit
runtime.Gosched()

这篇关于Golang:为什么os.Exit在goroutines中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!