In threading.Thread(target=x), is x shared or private?
It is private. Each thread has its own private invocation of x
.
This is similar to recursion, for example (regardless of multithreading). If x
calls itself, each invocation of x
gets its own "private" frame, with its own private local variables.
What is the preferred way to pass mutable variables to threads? Do I have to subclass Thread to update data?
I view the target
argument as a quick shortcut, good for quick experiments, but not much else. Using it where it ought not be used leads to all the limitations you describe in your question (and the hacks you describe in the possible solutions you contemplate).
Most of the time, you'd want to subclass threading.Thread
. The code creating/managing the threads would pass all mutable shared objects to your thread-classes' __init__
, and they should keep those objects as their attributes, and access them when running (within their run
method).
When do I need threading.local()?
You rarely do, so you probably don't.
I'd like to avoid _thread if possible to be pythonic
Without a doubt, avoid it.