Pablo Pablo - 3 years ago 100
Python Question

Does threading.local use locks for access?

Is there a

being done under the covers in the following statement:

my_thread_local = threading.local()
my_thread_local.some_value = 1

How about this one:

local_variable = my_thread_local.some_value

Answer Source

Only if the fallback implementation is in use.

If thread-local storage isn't otherwise provided (that is, if Py_HAVE_NATIVE_TLS is not defined when the interpreter is compiled), an implementation will be used which involves explicit locking.

On platforms with a proper native implementation, there's thus no need for the Python runtime to emulate this feature, and thus no need for locking at the Python runtime layer.

As of this writing (in July 2017), the fallback implementation was recently removed from the development branch of Python 3 (which no longer has any thread module for BeOS or other obscure operating systems which were formerly supported). Thus, on future releases of Python 3, a native version of thread-local storage will always be in use when threading is available at all.


  • Are you on Python 2.x?
    • Are you on Windows? Native thread-local storage is available.
    • Are you on any non-Windows platform? Python is using a locking-based implementation.
  • Are you on Python 3.1 or later?
    • Are you on Windows? Native thread-local storage is available.
    • Are you on modern Linux, MacOS, or another platform that implements POSIX threads? Native thread-local storage is available.
    • Are you on a non-Windows platform that doesn't support the pthreads API? You either won't have threading support at all, or thread-local storage will involve locking.

(Python 3.0 is intentionally not covered here: The native thread-local storage implementations present in both 2.7 and 3.1 and later aren't present in 3.0 at the same spot in the code where they're hosted in other versions, and I'm not considering it worth my time to dig down to determine whether the functionality had temporarily moved or if it's just missing outright).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download