1

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!

Kyle
  • 831
  • 1
  • 9
  • 17

1 Answers1

2

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.

Community
  • 1
  • 1
Fernando Matsumoto
  • 2,697
  • 1
  • 18
  • 24
  • Thanks! Is the second code runs faster than the first one, or they should spend more or less the same time? In other words, in the first case do other goroutines need to wait for previous goroutine finish copying function "test2" to their own thread? – Kyle Oct 01 '15 at 19:00
  • @Kyle No. In the first case, the function is not copied to its own thread. It is defined once and, every time it is called in a new [goroutine](https://golang.org/doc/effective_go.html#goroutines) that same code is executed with a new stack. – Fernando Matsumoto Oct 01 '15 at 19:11
  • Hey @FernandoMatsumoto it's being a while since you answered it but I wonder if you know any documentation that talks about this case for functions. Thanks! – HNL Jun 27 '21 at 13:15