我想知道Python内置容器(列表、向量、集合...)是否是线程安全的?或者我是否需要为我的共享变量实现锁定/解锁环境?
您需要为将在 Python 中修改的所有共享变量实现自己的锁定。您不必担心从不会被修改的变量中读取(即并发读取是可以的),因此不可变类型(frozenset
, tuple
, str
) are probably安全,但不会造成伤害。对于你将要改变的事情 -list
, set
, dict
以及大多数其他对象,您应该拥有自己的锁定机制(虽然就地操作在大多数对象上都可以,但线程可能会导致超级讨厌的错误 - 您也可以实现锁定,这非常简单)。
顺便说一句,我不知道你是否知道这一点,但在 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:
blocks:
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)
关于 Python 中线程同步的一些非常好的信息 https://web.archive.org/web/20201101025814id_/http://effbot.org/zone/thread-synchronization.htm.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)