0

In Python3.6, I use threading.local() to store some status for thread. Here is a simple example to explain my question:

    import threading

    class Test(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
            self.local = threading.local()
            self.local.test = 123

        def run(self):
            print(self.local.test)

When I start this thread:

t = Test()
t.start()

Python gives me an error:

AttributeError: '_thread._local' object has no attribute 'test'

It seems the test atrribute can not access out of the __init__ function scope, because I can print the value in the __init__ function after local set attribute test=123.

Is it necessary to use threading.local object inside in a Thread subclass? I think the instance attributes of a Thread instance could keep the attributes thread safe.

Anyway, why the threading.local object not work as expected between instance function?

1
  • If you want to attach data to a Thread object in a way that's visible from all threads, you don't need threading.local. Just assign to the Thread's instance variables directly. Commented Mar 20, 2018 at 3:38

2 Answers 2

4

When you constructed your thread you were using a DIFFERENT thread. when you execute the run method on the thread you are starting a NEW thread. that thread does not yet have a thread local variable set. this is why you do not have your attribute it was set on the thread constructing the thread object and not the thread running the object.

Sign up to request clarification or add additional context in comments.

Comments

2

As stated in https://docs.python.org/3.6/library/threading.html#thread-local-data:

The instance’s values will be different for separate threads.

Test.__init__ executes in the caller's thread (e.g. the thread where t = Test() executes). Yes, it's good place to create thread-local storage (TLS).

But when t.run executes, it will have completely diffferent contents -- the contents accessible only within the thread t.

TLS is good when You need to share data in scope of current thread. It like just a local variable inside a function -- but for threads. When the thread finishes execution -- TLS disappears.

For inter-thread communication Futures can be a good choice. Some others are Conditional variables, events, etc. See threading docs page.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.