[英]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.