您需要为将在Python中修改的所有共享变量实现自己的锁定。你不必担心从不会被修改的变量读(即并发读取都OK了),所以稳定的类型(frozenset
,tuple
,str
)都可能是 安全的,但它不会伤害。对于你将要改变的东西- ,list
,set
,dict
和大多数其他的对象,你应该有自己的锁定机制(而就地操作都OK在大多数的这些,线程可以导致超级讨厌的错误- 你还不如很好地实现锁定,这非常容易)。
顺便说一句,我不知道您是否知道,但是锁定在Python中非常容易-创建一个threading.lock对象,然后您可以像这样获取/释放它:
import threading
list1Lock = threading.Lock()
with list1Lock:
# change or read from the list here
# continue doing other stuff (the lock is released when you leave the with block)
在Python 2.5中,执行from __future__ import with_statement
; Python 2.4及更低版本没有此功能,因此您需要将acquire()/ release()调用放在try:...finally:
块中:
import threading
list1Lock = threading.Lock()
try:
list1Lock.acquire()
# change or read from the list here
finally:
list1Lock.release()
# continue doing other stuff (the lock is released when you leave the with block)