我想知道 Python 内置容器(list、vector、set...)是否是线程安全的?还是我需要为我的共享变量实现锁定/解锁环境?
最佳答案
您需要为所有将在 Python 中修改的共享变量实现自己的锁定。你不必担心从不会被修改的变量中读取(即并发读取是可以的),所以不可变类型(frozenset
、tuple
、str
) 是可能安全的,但它不会受到伤害。对于您将要更改的内容 - 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)
Some very good information about thread synchronization in Python .
关于python - Python 内置容器是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2227169/