dongyi7669 2015-10-01 18:19
浏览 21
已采纳

用goroutines调用非goroutine函数

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? 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!

  • 写回答

1条回答 默认 最新

  • dongxichan8627 2015-10-01 18:47
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起