我有一个用 python 构建的 webapp,运行在粘贴服务器上。如果我已经声明了一个将状态分配给方法范围变量的@staticmethod,我是否必须使用例如threading.RLock()(或者有更好的方法)来保护它以防止多个HTTP请求(我假设粘贴为服务器包含某种线程池,用于处理传入请求)以免干扰彼此的状态?
我应该指出我正在使用 Grok 作为我的框架。
所以-
@staticmethod
def doSomeStuff():
abc = 1
...some code...
abc = 5
鉴于上述情况,在线程之间的 grok/paste 内部是否是线程安全的(同样,假设请求是在线程中处理的?)
最佳答案
局部变量是为每个方法调用单独创建的,无论是静态方法、类方法、非静态方法还是独立函数,与 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
在这方面没有任何改变。
关于python - 如果我的 python webapp 中有一个 @staticmethod,我是否需要使用 threading.RLock() 来保护它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9957224/