为每个方法调用单独创建局部变量,无论是静态方法、类方法、非静态方法还是独立函数,与 Java 中的方法相同。除非您将对这些对象的引用显式地复制到外部某处,以便它们在该方法中存在并且可以从其他线程访问,否则您不必锁定任何东西。
例如,除非CoolClass
在实例之间使用任何共享状态,否则这是安全的:
def my_safe_method(*args):
my_cool_object = CoolClass()
my_cool_object.populate_from_stuff(*args)
return my_cool_object.result()
这可能是不安全的,因为对象引用可能在线程之间共享(取决于做什么get_cool_inst
):
def my_suspicious_method(*args):
my_cool_object = somewhere.get_cool_inst()
my_cool_object.populate_from_stuff(*args)
# another thread received the same instance
# and modified it
# (my_cool_object is still local, but it's a reference to a shared object)
return my_cool_object.result()
publish
如果共享参考,这也可能不安全:
def my_suspicious_method(*args):
my_cool_object = CoolClass()
# puts somewhere into global namespace, other threads access it
publish(my_cool_object)
my_cool_object.prepare(*args)
# another thread modifies it now
return my_cool_object.result()
编辑:您提供的代码示例是完全线程安全的,@staticmethod
在这方面没有改变任何东西。