Reputation: 861
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!
Upvotes: 1
Views: 2478
Reputation: 2727
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.
Upvotes: 2