3

我有一个内置在 python 中的 webapp 运行粘贴服务器。如果我已经声明了一个将状态分配给方法范围变量的@staticmethod,我是否必须使用例如 threading.RLock() 来保护它(或者有更好的方法)以防止多个 HTTP 请求(我假设粘贴为服务器包含某种用于服务传入请求的线程池)以免干扰彼此的状态?

我应该指出我使用 Grok 作为我的框架。

所以 -

@staticmethod
def doSomeStuff():
 abc = 1
 ...some code...
 abc = 5

鉴于上述情况,在线程之间的 grok/paste 中是否是线程安全的(再次假设请求是在线程中处理的?)

4

1 回答 1

3

为每个方法调用单独创建局部变量,无论是静态方法、类方法、非静态方法还是独立函数,与 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在这方面没有改变任何东西。

于 2012-03-31T19:02:37.343 回答