Question

I have a webapp built in python running off the paste server. If I have declared an @staticmethod that assigns state to method-scoped variables do I have to protect it with eg threading.RLock() (or is there a better way) in order to prevent multiple HTTP requests (I'm assuming paste as a server contains some sort of threadpool for serving incoming requests) from interfering with eachother's state?

I should point out I am using Grok as my framework.

so -

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

given the above, is it thread safe inside grok/paste between threads (again, assuming requests are dealt with in threads?)

Was it helpful?

Solution

Local variables are created for each method call separately, no matter if it's static method, class method, non-static method or a stand-alone function, the same way as in Java. Unless you copy the references to those objects somewhere outside explicitly, so that they survive the method and can be accessed from other threads, you don't have to lock anything.

For example, this is safe unless CoolClass uses any shared state between instances:

def my_safe_method(*args):
    my_cool_object = CoolClass()
    my_cool_object.populate_from_stuff(*args)
    return my_cool_object.result()

This is likely to be unsafe since the object reference may be shared between the threads (depends on what get_cool_inst does):

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()

This can be unsafe too, if publish shares the reference:

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()

EDIT: The code sample you've provided is completely thread safe, @staticmethod didn't change anything in that respect.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top