调用非goroutine函数时使用goroutine

huangapple go评论70阅读模式
英文:

Calling non-goroutine function with goroutines

问题

我有一部分脚本,格式如下:

func main() {
    for i=0;i<1000000;i++ {
        go test()
    }
}
func test() {
    a := test2()
}
func test2()(var int) {
    //一堆操作
    return var
}

我运行了很多次迭代,一直都没问题。我想知道是否有可能两个或更多的goroutine同时调用函数"test2()"并导致崩溃?下面的格式是否比之前的更好?

func main() {
    for i=0;i<1000000;i++ {
        go test()
    }
}
func test() {
    test2 := func()(var int){
        //一堆操作
        return var
    }
    a := test2()
}

非常感谢!

英文:

I have part of a script with the following format:

func main() {
  for i=0;i&lt;1000000;i++ {
  	go test()
  }
}
func test() {
    a := test2()
}
func test2()(var int) {
    //a bunch of operations
    return var
}

I run a lot of iterations and it always work. I'm wondering is there any chance that two or more goroutines calling function "test2()" at the same time and cause a crash? Is the following format anyway better then the previous one?

func main() {
    for i=0;i&lt;1000000;i++ {
    	go test()
    }
}
func test() {
    test2 := func()(var int){
	    //a bunch of operations
	    return var
    }
    a := test2()
}

Thank you very much!

答案1

得分: 2

不,除非你的代码有问题(例如除以零)或者你明确调用了panic(),否则你的函数不会崩溃。如果它不访问任何字段(或者方法的文档没有指明可以并发调用),那么你的函数是线程安全的

编辑:第一个代码更好。虽然两者的性能应该非常相似,因为它们运行相同的代码,但第一个代码更容易阅读。在第二个代码块中,你定义了多个函数,可能会有一点性能损失,但这可能会被编译器优化掉。

英文:

No, your function will not crash, unless there is something wrong in your code (i.e. division by zero) or you explicitly call panic(). If it doesn't access any fields (or methods whose documentation doesn't specify they may be called concurrently), then your function is thread-safe.

EDIT: The first code is better. Although both should have very similar performance, since they are running the same code, the first is easier to read. There may be a small performance penalty in your second code block, since you are defining a function multiple times, but that is probably optimized away by the compiler.

huangapple
  • 本文由 发表于 2015年10月2日 02:19:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/32894299.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定