局部變量爲每個方法創建(再次,假設請求的線程處理?)不管是靜態方法,類方法,非靜態方法還是獨立函數,都可以單獨調用,與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
沒有改變這方面的任何內容。
通過方法範圍的變量,你是指本地的變量嗎?代碼示例會很有幫助。 – bereal 2012-03-31 17:06:57
對不起,在方法中分配的局部變量。 – rutherford 2012-03-31 18:44:28
現在,我們來澄清另一件事。這些變量是本地的,但那些是對象引用,不是嗎?如果是這樣,他們是否創建並死於方法內部,或者是從別的地方獲取/保存? – bereal 2012-03-31 18:53:40