is a Python dictionary thread-safe when keys are thread IDs?

断了今生、忘了曾经 提交于 2021-01-28 00:22:20

问题


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()]
        # ...

回答1:


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.

The moment any of these hooks are implemented in Python code, the GIL can be released between bytecodes and all bets are off.

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.

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.



来源:https://stackoverflow.com/questions/23157089/is-a-python-dictionary-thread-safe-when-keys-are-thread-ids

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!