简体   繁体   English

用goroutines调用非goroutine函数

[英]Calling non-goroutine function with goroutines

I have part of a script with the following format: 我有以下格式的脚本的一部分:

func main() {
  for i=0;i<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? 我想知道两个或更多goroutines同时调用函数“ test2()”并导致崩溃的可能性吗? Is the following format anyway better then the previous one? 无论如何,以下格式是否比前一种更好?

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

Thank you very much! 非常感谢你!

No, your function will not crash, unless there is something wrong in your code (ie division by zero) or you explicitly call panic() . 不,您的函数不会崩溃,除非您的代码有问题(即被零除)或您明确调用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. 由于您多次定义一个函数,因此第二个代码块中的性能可能会有所降低,但是编译器可能会对其进行优化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 调用函数返回时 Goroutine 终止 - Goroutine Termination on Calling Function Return 创建goroutine并设置最大goroutine - Create goroutine and set maximum goroutines 从goroutine调用阻止的DLL函数? - Calling a blocking DLL function from a goroutine? 来自 function 的递归调用以 goroutine 和惯用方式开始,以在所有 worker goroutine 完成后继续调用 - Recursive calls from function started as goroutine & Idiomatic way to continue caller when all worker goroutines finished 我们可以限制 function 从 goroutine 一次调用一次吗 - Can we restrict function calling once at a time from goroutine 如何等待其他多个Goroutine的单个Goroutine响应? - How can i Await a Single Goroutine Response on Multiple other Goroutines? 当主/父 goroutine 退出或返回时,未完成的 goroutine 会发生什么? - What happens to unfinished goroutines when the main/parent goroutine exits or returns? 将数据从一个 goroutine 发送到多个其他 goroutine - Sending data from one goroutine to multiple other goroutines 作为goroutines启动的3个不同的funcs生成相同的goroutine(显然忽略了参数) - 3 different funcs launched as goroutines produce the same goroutine (apparently ignore arguments) Goroutines - 将关键数据发送到单个 goroutine 并等待结果 - Goroutines - send critical data to the single goroutine and wait for result
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM