Python thread_local data

Viewed 134

Python threading module documentation recommends using threading.local() for storing data that is not to be shared between threads.

Is there any fundamental problem using

threading.current_thread().x= 42

instead of

mydata= threading.local()
mydata.x= 42

?

The former pollutes the namespace of the thread object a little, but that can be handled if needed. Other than that, both approaches seem to work, but there must be a reason why the latter is recommended in the docs.

1 Answers

threading.local() object can be accessed from anywhere, but it will return different data depending on thread, where this object was accessed.

Example:

mydata= threading.local()
mydata.x= 42

def foo():
    mydata.x = 'Hello from thread'
    print(mydata.x)

thread1 = threading.Thread(target=foo)
thread1.start()
thread1.join()

>>> 'Hello from thread'

print(mydata.x)
>>> 42

With threading.current_thread().x you cannot attain that behavior.

Update

More clarifying example:

import threading
from threading import current_thread

threadLocal = threading.local()

def hello():
    initialized = getattr(threadLocal, 'initialized', None)
    if initialized is None:
        print('Nice to meet you', current_thread().name)
        threadLocal.initialized = True
    else:
        print('Welcome back', current_thread().name)


hello()
hello()

# output
'Nice to meet you MainThread'
'Welcome back MainThread'
Related