问题描述
仅使用当前线程的线程ID进行读取或写入时,Python词典线程是否安全?喜欢
Is a Python dictionary thread safe when using the thread ID of the current thread only to read or write? Like
import thread
import threading
class Thread(threading.Thread):
def __init__(self, data):
super(Thread, self).__init__()
self.data = data
def run(self):
data = self.data[thread.get_ident()]
# ...
推荐答案
如果 data
是标准的Python字典,则 __ getitem __
调用为完全用C实现,对 thread.get_ident()
返回的整数值的 __ hash __
方法也是如此.此时, data .__ getitem __(<线程标识符>)
调用是线程安全的.写入 data
时也是如此; data .__ setitem __()
调用完全在C中处理.
If data
is a standard Python dictionary, the __getitem__
call is implemented entirely in C, as is the __hash__
method on the integer value returned by thread.get_ident()
. At that point the data.__getitem__(<thread identifier>)
call is thread safe. The same applies to writing to data
; the data.__setitem__()
call is entirely handled in C.
一旦这些钩子中的任何一个都用Python代码实现,就可以在字节码之间释放GIL,并且所有下注都将关闭.
The moment any of these hooks are implemented in Python code, the GIL can be released between bytecodes and all bets are off.
所有这些都假设您正在使用CPython.Jython,IronPython,PyPy和其他python实现可能会在何时切换线程方面做出不同的决定.
This all makes the assumption you are using CPython; Jython, IronPython, PyPy and other python implementations may make different decisions on when to switch threads.
最好使用 threading.local()
映射对象而非,因为可以确保为您提供线程本地的命名空间.不过,它仅支持属性访问.
You'd be better of using the threading.local()
mapping object instead, as that is guaranteed to provide you with a thread-local namespace. It only supports attribute access though.
这篇关于键是线程ID时,Python字典是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!