Question

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()]
        # ...
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top