这个函数并发执行安全吗?
def isSafe( i:Int) = {
var count = i
var acc = 0
while(count!=0){
acc += i*i
count -= 1
}
acc
}
def isSafe( i:Int) = {
var count = i
var acc = 0
while(count!=0){
acc += i*i
count -= 1
}
acc
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果安全意味着它返回相同的结果,而与调用它的线程数量和顺序无关,那么是的,它是安全的。这是因为它不修改任何共享内存位置,仅修改其局部变量。
If by safe you mean that it returns the same result independently of how many threads invoke it and in which order, then yes, it's safe. This is because it doesn't modify any shared memory locations, only its local variables.
它是安全的,没有可能导致跨线程污染的共享状态。
它也过于复杂,以下定义既短又快:
It's safe, there's no shared state that could lead to cross-thread contamination.
It's also massively over-complicated, the following definition is both shorter and faster: