2016-09-16 27 views
0

Fredrik Lundh的文章標題爲Thread Synchronization Mechanisms in Python給出了下面的例子,表明多個線程操作可能導致不準確的值。瞭解線程同步

counter = 0 

def process_item(item): 
    global counter 
    ... do something with item ... 
    counter += 1 

它接着說,這些東西是線程安全的:

reading or replacing a single instance attribute 
reading or replacing a single global variable 
fetching an item from a list 
modifying a list in place (e.g. adding an item using append) 
fetching an item from a dictionary 
modifying a dictionary in place (e.g. adding an item, or calling the clear method) 

但不只是更新一個全局變量的代碼示例,因此將是線程安全的呢?

我在這裏錯過了什麼?

+0

「更新」!=「替換」更新取決於以前的狀態(所以它被讀取,修改,寫入),替換不是(它只是一個寫)。還要注意的是,如果鍵是用戶定義的對象(因爲調用了__eq__或__hash__方法,並且GIL可以被轉移到不同的線程,所以在技術上修改'dict'並不總是在Python中是線程安全的正在執行,破壞原子性)。 – ShadowRanger

回答

3

在Python代碼:

counter += 1 

是相同的話:

counter = counter + 1 

因此該值的查找是單獨的更新。

+0

哦,所以計數+ = 1會被視爲「閱讀和替換」而不是「閱讀或替換」? – ealeon

+0

@ealeon:'count + = 1'正在更新需要讀取其當前值,更改它並將其寫回的值。 – martineau