Skip to content Skip to sidebar Skip to footer

Is A Python Dictionary Thread-safe When Keys Are Thread Ids?

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): d

Solution 1:

Ifdata 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.

Post a Comment for "Is A Python Dictionary Thread-safe When Keys Are Thread Ids?"